我正在開發Android應用程序,在該應用程序中,我需要在上傳聯繫人之前向用戶詢問聯繫人權限。以下是我用於聯繫許可Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
的代碼。所有Android版本的聯繫權限
但問題是我需要每次都要向Android M請求聯繫權限。如何要求聯繫權限應該適用於所有SDK版本?
private void getContact(){
// Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
// startActivityForResult(intent, PICK_CONTACT);
}
public void askForContactPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_CONTACTS)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Contacts access needed");
builder.setPositiveButton(android.R.string.ok, null);
builder.setMessage("please confirm Contacts access");//TODO put real question
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(
new String[]
{Manifest.permission.READ_CONTACTS}
, PERMISSION_REQUEST_CONTACT);
}
});
builder.show();
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CONTACTS},
PERMISSION_REQUEST_CONTACT);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}else{
getContact();
}
}
else{
getContact();
}
}
int PERMISSION_REQUEST_CONTACT = 1;
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// getContact();
Toast.makeText(getApplicationContext(),"Permission is Done",Toast.LENGTH_LONG).show();
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
Toast.makeText(getApplicationContext(),"No permission for contacts",Toast.LENGTH_LONG).show();
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
在M以下,您不需要編寫除Manifest文件外的任何外部代碼。 – Spartan
@PushpendraChoudhary感謝您的評論。其實我的要求是顯示聯繫權限的消息。我們可以通過編程的方式要求聯繫人權限嗎? –
問題在於Android M以下,它沒有要求聯繫權限。我需要在此SDK級別下顯示一個對話框。 –