Getting contact information on mobile phones is a very common function, which should be implemented in recent projects. Considering that APP will probably have this function in the future, we can simply put this small function into a class, so that we don't need to write code in the future when we meet this requirement, so we can copy this kind of function directly and use it.
The following is the effect map of getting contact demo, which is simple and can explain the problem.
In the daily use of Android mobile phones, it is a common problem to get contact portraits according to the phone number. In this paper, an example is given to illustrate the implementation code for Android to get the contact's head image based on the phone number. Share it for your reference. The specific methods are as follows:
First, through ContentProvider, you can access data such as contacts in Android. The commonly used Uri are:
- Contact information Uri: content://com.android.contacts/raw_contacts
- Contact number Uri: content://com.android.contacts/data/phones
It also provides the function of retrieving data table data according to telephone number by data/phones/filter/number and returning a data set. Then get the contact_id of the contact through the data set, open the InputStream of the head image according to the contact_id, and finally get the head image of the contact with BitmapFactory.decodeStream().
// Get the Contact Portrait by Number
public Bitmap get_people_image(String p_number) {
Bitmap bmp_head=null;
// Get Uri
Uri uriNumber2Contacts = Uri.parse("content://com.android.contacts/"
+ "data/phones/filter/" + p_number);
// Query Uri and return data sets
Cursor cursorCantacts = resolver.query(
uriNumber2Contacts,
null,
null,
null,
null);
// If the contact exists
if (cursorCantacts.getCount() > 0) {
// Move to the first data
cursorCantacts.moveToFirst();
// Get the contact_id of the contact
Long contactID = cursorCantacts.getLong(cursorCantacts.getColumnIndex("contact_id"));
// Uri to get contact_id
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactID);
// Open InputStream for the head image
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
// Getting bitmap from InputStream
bmp_head = BitmapFactory.decodeStream(input);
}
return bmp_head;
}
Fill in contact information (contact name, phone number, avatar) into the collection. The following are the key codes:
private List<Map<String, String>> fillListContent(ContentResolver resolver) {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
// Find out the data that has not been deleted: deleted=0
Cursor cursor_raw_Contacts = resolver.query(
Uri.parse(uri_raw_contacts), new String[]{"_id",
"display_name"}, "deleted=0", null, null);
while (cursor_raw_Contacts.moveToNext()) {
Map<String, String> map = new HashMap<String, String>();
String contacts_id = cursor_raw_Contacts
.getString(cursor_raw_Contacts.getColumnIndex("_id"));
String contacts_display_name = cursor_raw_Contacts
.getString(cursor_raw_Contacts
.getColumnIndex("display_name"));
map.put("id", contacts_id);
map.put("display_name", contacts_display_name);
// Query the phone information of the data table based on raw_contact_id, and pay attention to the uri path
Cursor cursor_phones = resolver.query(Uri.parse(uri_data_phones),
new String[]{"data1"}, "raw_contact_id=?",
new String[]{contacts_id}, null);
StringBuilder sb = new StringBuilder();
while (cursor_phones.moveToNext()) {
sb.append(cursor_phones.getString(0)).append(" ");
}
map.put("phones", sb.toString());
cursor_phones.close();
list.add(map);
}
cursor_raw_Contacts.close();
return list;
}
Next, let's show this effect step by step. 1. Navigation bar with alphabetical index on the right We can find many similar ones on the internet. You can find one you like or even write one by yourself. Here I find one with wave effect on the internet. It looks cool. This is the original address: https://github.com/AlexLiuSheng/AnimSideBar Then I imported it into our project and modified some of the code. Here is SideBar.Java in my project.
package com.czb.contacts.sidebar;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;
import com.czb.contacts.R;
/**
* Created by Allen Liu on 2016/5/12.
*/
public class SideBar extends TextView {
private String[] letters = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z", "#"};
private Paint textPaint;
private Paint bigTextPaint;
private Paint scaleTextPaint;
private Canvas canvas;
private int itemH;
private int w;
private int h;
/**
* Font size in general
*/
float singleTextH;
/**
* Zoom out of the original width
*/
private float scaleWidth = dp(100);
/**
* Sliding Y
*/
private float eventY = 0;
/**
* Scaling multiple
*/
private int scaleTime = 1;
/**
* Scale the number of item s, that is, the opening size
*/
private int scaleItemCount = 6;
private ISideBarSelectCallBack callBack;
public SideBar(Context context) {
super(context);
init(null);
}
public SideBar(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public SideBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SideBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs);
}
public void setDataResource(String[] data){
letters=data;
invalidate();
}
public void setOnStrSelectCallBack(ISideBarSelectCallBack callBack){
this.callBack=callBack;
}
/**
* Set font zoom ratio
* @param scale
*/
public void setScaleTime(int scale){
scaleTime=scale;
invalidate();
}
/**
* Set the number of zoom fonts, that is, the opening size
* @param scaleItemCount
*/
public void setScaleItemCount(int scaleItemCount){
this.scaleItemCount=scaleItemCount;
invalidate();
}
private void init(AttributeSet attrs) {
// setPadding(dp(10), 0, dp(10), 0);
if(attrs!=null) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.SideBar);
scaleTime= typedArray.getInteger(R.styleable.SideBar_scaleTime,1);
scaleItemCount=typedArray.getInteger(R.styleable.SideBar_scaleItemCount,6);
}
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(getCurrentTextColor());
textPaint.setTextSize(getTextSize());
textPaint.setTextAlign(Paint.Align.CENTER);
bigTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bigTextPaint.setColor(getCurrentTextColor());
bigTextPaint.setTextSize(getTextSize() * (scaleTime+2) );
bigTextPaint.setTextAlign(Paint.Align.CENTER);
scaleTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
scaleTextPaint.setColor(getCurrentTextColor());
scaleTextPaint.setTextSize(getTextSize() * (scaleTime + 1));
scaleTextPaint.setTextAlign(Paint.Align.CENTER);
}
private int dp(int px) {
return DensityUtil.dip2px(getContext(), px);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
if(event.getX()>(w-getPaddingRight()-singleTextH-10)) {
eventY = event.getY();
invalidate();
return true;
}else{
eventY = 0;
invalidate();
break;
}
case MotionEvent.ACTION_CANCEL:
eventY = 0;
invalidate();
return true;
case MotionEvent.ACTION_UP:
if(event.getX()>(w-getPaddingRight()-singleTextH-10)) {
eventY = 0;
invalidate();
return true;
}else
break;
}
return super.onTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
this.canvas = canvas;
DrawView(eventY);
}
private void DrawView(float y) {
int currentSelectIndex = -1;
if (y != 0) {
for (int i = 0; i < letters.length; i++) {
float currentItemY = itemH * i;
float nextItemY = itemH * (i + 1);
if (y >= currentItemY && y < nextItemY) {
currentSelectIndex = i;
if(callBack!=null){
callBack.onSelectStr(currentSelectIndex,letters[i]);
}
//Large letters
Paint.FontMetrics fontMetrics = bigTextPaint.getFontMetrics();
float bigTextSize = fontMetrics.descent - fontMetrics.ascent;
canvas.drawText(letters[i], w - getPaddingRight() - scaleWidth - bigTextSize, singleTextH + itemH * i, bigTextPaint);
}
}
}
drawLetters(y, currentSelectIndex);
}
private void drawLetters(float y, int index) {
//No zoom in the first indentation, default to draw the original picture
if (index == -1) {
w = getMeasuredWidth();
h = getMeasuredHeight();
itemH = h / letters.length;
Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
singleTextH = fontMetrics.descent - fontMetrics.ascent;
for (int i = 0; i < letters.length; i++) {
canvas.drawText(letters[i], w - getPaddingRight(), singleTextH + itemH * i, textPaint);
}
//Draw a zoom when touching
} else {
//Traveling through all letters
for (int i = 0; i < letters.length; i++) {
//Starting Y coordinates of the letters to be drawn
float currentItemToDrawY = singleTextH + itemH * i;
float centerItemToDrawY;
if (index < i)
centerItemToDrawY = singleTextH + itemH * (index + scaleItemCount);
else
centerItemToDrawY = singleTextH + itemH * (index - scaleItemCount);
float delta = 1 - Math.abs((y - currentItemToDrawY) / (centerItemToDrawY - currentItemToDrawY));
Log.v("delta", letters[i] + "--->" + delta + "");
float maxRightX = w - getPaddingRight();
//If it's greater than 0, it's above y coordinates.
scaleTextPaint.setTextSize(getTextSize() + getTextSize() * delta);
float drawX = maxRightX - scaleWidth * delta;
//Flowering directly beyond the boundary
if (drawX > maxRightX)
canvas.drawText(letters[i], maxRightX, singleTextH + itemH * i, textPaint);
else
canvas.drawText(letters[i], drawX, singleTextH + itemH * i, scaleTextPaint);
//Parabolic implementation, no animation effect, too stiff
// canvas.save();
// canvas.translate(w-getPaddingRight(),0);
// double y1 = singleTextH + itemH * (index - scaleItemCount);
// double y2 = singleTextH + itemH * (index + scaleItemCount);
// double topY = y;
// double topX = -scaleWidth;
// double p = topX / ((topY - y1) * (topY - y2));
// for (int j = 1; j <= scaleItemCount; j++) {
// double currentY=singleTextH + itemH * i;
// canvas.drawText(letters[i], (float) (p * (currentY - y1) * (currentY - y2)), singleTextH + itemH * i, scaleTextPaint);
// }
// canvas.restore();
// }
}
}
}
public interface ISideBarSelectCallBack {
void onSelectStr(int index, String selectStr);
}
}
Then there are two custom attributes
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SideBar">
<attr name="scaleTime" format="integer"></attr>
<attr name="scaleItemCount" format="integer"></attr>
</declare-styleable>
</resources>
2. Tools for Transliterating Chinese Characters into Pinyin
We know that there are no interfaces and methods in Java to convert Chinese characters into Pinyin directly. Here, I can refer to another blog: Java/Android Chinese characters in Pinyin two methods, the pros and cons of comparison Then I chose to use a third-party jar package because it was smaller and more accurate. Here is my Cn2Spell.java
Depend on pinyin4j: compile'com.belerweb:pinyin4j:2.5.1'
package com.czb.contacts.util;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
/**
* Chinese Character Conversion Bit Chinese Pinyin, English Characters unchanged
*/
public class Cn2Spell {
public static StringBuffer sb = new StringBuffer();
/**
* Get the first letter of the Chinese character string, the English character remains unchanged.
* For example: Afi af
*/
public static String getPinYinHeadChar(String chines) {
sb.setLength(0);
char[] chars = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < chars.length; i++) {
if (chars[i] > 128) {
try {
sb.append(PinyinHelper.toHanyuPinyinStringArray(chars[i], defaultFormat)[0].charAt(0));
} catch (Exception e) {
e.printStackTrace();
}
} else {
sb.append(chars[i]);
}
}
return sb.toString();
}
/**
* Getting the first letter of a Chinese character string
*/
public static String getPinYinFirstLetter(String str) {
sb.setLength(0);
char c = str.charAt(0);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
if (pinyinArray != null) {
sb.append(pinyinArray[0].charAt(0));
} else {
sb.append(c);
}
return sb.toString();
}
/**
* Get Chinese Pinyin of Chinese Character Strings, English Characters unchanged
*/
public static String getPinYin(String chines) {
sb.setLength(0);
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
if (nameChar[i] > 128) {
try {
sb.append(PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0]);
} catch (Exception e) {
e.printStackTrace();
}
} else {
sb.append(nameChar[i]);
}
}
return sb.toString();
}
}
3. The names in the address book can be sorted according to Pinyin.
We chose to implement the comparable interface and rewrite the comparaTo method. Here is my ContactsModel.java
package com.czb.contacts.event;
import android.graphics.Bitmap;
import com.czb.contacts.util.Cn2Spell;
/**
* Created by Administrator on 2016/5/25.
*/
public class ContactsModel implements Comparable<ContactsModel> {
private String displayName; // Full name
private String phone;//Telephone number?
private String pinyin; // Phonetic Alphabet for Name
private String firstLetter; // The initials of Pinyin
private Bitmap bm_head;//Head portrait
public ContactsModel(String displayName,String phone,Bitmap bm_head) {
this.bm_head=bm_head;
this.phone=phone;
this.displayName = displayName;
pinyin = Cn2Spell.getPinYin(displayName); // Acquire Pinyin by Name
firstLetter = pinyin.substring(0, 1).toUpperCase(); // Get the initials of Pinyin and capitalize them
if (!firstLetter.matches("[A-Z]")) { // If not in A-Z, it defaults to ""
firstLetter = "#";
}
}
public Bitmap getBm_head() {
return bm_head;
}
public String getPhone() {
return phone;
}
public String getDisplayName() {
return displayName;
}
public String getPinyin() {
return pinyin;
}
public String getFirstLetter() {
return firstLetter;
}
@Override
public int compareTo(ContactsModel another) {
if (firstLetter.equals("#") && !another.getFirstLetter().equals("#")) {
return 1;
} else if (!firstLetter.equals("#") && another.getFirstLetter().equals("#")){
return -1;
} else {
return pinyin.compareToIgnoreCase(another.getPinyin());
}
}
}
The principle is very simple, that is, first according to the first letter judgment, the first letter is "" are placed at the end, are all "" or are all letters when the comparison is sorted according to the Pinyin.
4. It's only due to the East Wind that everything is ready. Then it's time to assemble these things.
activity_main.xml layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:sidebar="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.afei.indexlistview.MainActivity">
<RelativeLayout
android:id="@+id/rSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#C9C8CE">
<AutoCompleteTextView
android:id="@+id/acTextView"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="8dp"
android:background="@drawable/bg_white_r_shape"
android:completionThreshold="1"
android:drawableLeft="@mipmap/icon_sousuo"
android:gravity="center"
android:hint="Search for a contact"
android:padding="4dp"
android:singleLine="true"
android:textColor="#666666"
android:textSize="13sp" />
</RelativeLayout>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/rSearch" />
<com.czb.contacts.sidebar.SideBar
android:id="@+id/side_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_below="@id/rSearch"
android:paddingRight="10dp"
android:textColor="@color/colorPrimary"
android:textSize="13sp"
sidebar:scaleTime="1" />
</RelativeLayout>
Main Implementation Class MainActivity.java
package com.czb.contacts;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Toast;
import com.czb.contacts.adapter.SearchContactsAdapter;
import com.czb.contacts.adapter.SortAdapter;
import com.czb.contacts.event.ContactsModel;
import com.czb.contacts.sidebar.SideBar;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private SideBar sideBar;
private ArrayList<ContactsModel> dataList;
private AutoCompleteTextView acTextView;
//Get the corresponding phone number of the contact person
private String uri_data_phones = "content://com.android.contacts/data/phones";
//Get the contact (ID,displayName)
private String uri_raw_contacts = "content://com.android.contacts/raw_contacts";
private List<Map<String, String>> contactsList;
private ContentResolver resolver;
private String[] mPermissionList={ Manifest.permission.READ_CONTACTS,Manifest.permission.WRITE_CONTACTS};
private SearchContactsAdapter cAdapter;
private List<String> mContacts = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkPermissionIsOK()) {
initView();
initData();
} else {
requestPermission();
}
}
private void initData() {
resolver = getContentResolver();
contactsList = fillListContent(resolver);
if (contactsList != null && contactsList.size() > 0) {
for (Map<String, String> maps : contactsList) {
String displayName = maps.get("display_name");
String phones = maps.get("phones");
if (TextUtils.isEmpty(displayName))
displayName = "";
if (TextUtils.isEmpty(phones))
phones = "";
ContactsModel contactsModel = new ContactsModel(displayName, phones,get_people_image(phones));
dataList.add(contactsModel);
mContacts.add(displayName);
}
}
Collections.sort(dataList); // To sort list s, you need to let User implement Comparable interface rewrite compareTo method
SortAdapter adapter = new SortAdapter(this, dataList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ContactsModel contactsModel = dataList.get(position);
Toast.makeText(MainActivity.this, contactsModel.getPhone(), Toast.LENGTH_SHORT).show();
}
});
cAdapter=new SearchContactsAdapter(this, android.R.layout.simple_list_item_1, mContacts, SearchContactsAdapter.ALL);
acTextView.setAdapter(cAdapter);
acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = cAdapter.getItem(position).toString();
Toast.makeText(MainActivity.this,item, Toast.LENGTH_SHORT).show();
}
});
}
// Get the Contact Portrait by Number
public Bitmap get_people_image(String p_number) {
Bitmap bmp_head=null;
// Get Uri
Uri uriNumber2Contacts = Uri.parse("content://com.android.contacts/"
+ "data/phones/filter/" + p_number);
// Query Uri and return data sets
Cursor cursorCantacts = resolver.query(
uriNumber2Contacts,
null,
null,
null,
null);
// If the contact exists
if (cursorCantacts.getCount() > 0) {
// Move to the first data
cursorCantacts.moveToFirst();
// Get the contact_id of the contact
Long contactID = cursorCantacts.getLong(cursorCantacts.getColumnIndex("contact_id"));
// Uri to get contact_id
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactID);
// Open InputStream for the head image
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
// Getting bitmap from InputStream
bmp_head = BitmapFactory.decodeStream(input);
}
return bmp_head;
}
private List<Map<String, String>> fillListContent(ContentResolver resolver) {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
// Find out the data that has not been deleted: deleted=0
Cursor cursor_raw_Contacts = resolver.query(
Uri.parse(uri_raw_contacts), new String[]{"_id",
"display_name"}, "deleted=0", null, null);
while (cursor_raw_Contacts.moveToNext()) {
Map<String, String> map = new HashMap<String, String>();
String contacts_id = cursor_raw_Contacts
.getString(cursor_raw_Contacts.getColumnIndex("_id"));
String contacts_display_name = cursor_raw_Contacts
.getString(cursor_raw_Contacts
.getColumnIndex("display_name"));
map.put("id", contacts_id);
map.put("display_name", contacts_display_name);
// Query the phone information of the data table based on raw_contact_id, and pay attention to the uri path
Cursor cursor_phones = resolver.query(Uri.parse(uri_data_phones),
new String[]{"data1"}, "raw_contact_id=?",
new String[]{contacts_id}, null);
StringBuilder sb = new StringBuilder();
while (cursor_phones.moveToNext()) {
sb.append(cursor_phones.getString(0)).append(" ");
}
map.put("phones", sb.toString());
cursor_phones.close();
list.add(map);
}
cursor_raw_Contacts.close();
return list;
}
private void initView() {
sideBar = (SideBar) findViewById(R.id.side_bar);
acTextView = ((AutoCompleteTextView) findViewById(R.id.acTextView));
listView = (ListView) findViewById(R.id.listView);
dataList = new ArrayList();
sideBar.setOnStrSelectCallBack(new SideBar.ISideBarSelectCallBack() {
@Override
public void onSelectStr(int index, String selectStr) {
for (int i = 0; i < dataList.size(); i++) {
if (selectStr.equalsIgnoreCase(dataList.get(i).getFirstLetter())) {
listView.setSelection(i); // Choose the place where the initials appear
return;
}
}
}
});
}
//If you want to run on android 6.0 system, you need to get permission dynamically. If you don't have permission, sharing sdk will make mistakes and adapt to android 6.0 system.
@TargetApi(Build.VERSION_CODES.M)
private void requestPermission() {
List<String> permissionsNeeded = new ArrayList();
final List<String> permissionsList = new ArrayList();
for (int i = 0; i < mPermissionList.length; i++) {
final String s = mPermissionList[i];
String name = s.substring(s.lastIndexOf('.') + 1);
if (!TextUtils.isEmpty(name))
if (!addPermission(permissionsList, s))
permissionsNeeded.add(name);
}
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE);
return;
}
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE);
return;
}
}
@TargetApi(Build.VERSION_CODES.M)
private boolean checkPermissionIsOK() {
boolean isPermission = false;
for (int i = 0; i < mPermissionList.length; i++) {
if ((checkSelfPermission(mPermissionList[i]) == PackageManager.PERMISSION_GRANTED)
&& (checkSelfPermission(mPermissionList[i++]) == PackageManager.PERMISSION_GRANTED)) {
isPermission = true;
} else {
isPermission = false;
}
}
return isPermission;
}
@TargetApi(Build.VERSION_CODES.M)
private boolean addPermission(List<String> permissionsList, String permission) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
private final int REQUEST_CODE = 123;
int flagPermission = 0;
boolean isflag = true;
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, final String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE || requestCode == 456) {
boolean isRequest = false;
if (grantResults != null) {
for (int i = 0; i < grantResults.length; i++) {
flagPermission = i;
final int result = grantResults[i];
if (result == PackageManager.PERMISSION_GRANTED) {
isRequest = true;
} else {
//Application authority
requestPermissions(new String[]{permissions[flagPermission]}, 456);
}
}
if (isRequest) {
if (isflag) {
initView();
initData();
}
}
}
}
}
}