Jaw*_*rsi 2 android android-6.0-marshmallow
我想在我的应用程序中。如果permission已经授予不在dialogandroid中显示这是我的代码
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
requestContactsPermissions();
break;
case R.id.button1:
// requestCameraPermissions();
Toast.makeText(mcontext, "Hello", Toast.LENGTH_LONG).show();
break;
}
}
private void requestContactsPermissions() {
boolean requestPermission = PersimissionTest.requestContactsPermissions(this);
if (requestPermission == true) {
ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACTS, REQUEST_ID);
} else {
ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACTS, REQUEST_ID);
}
}
Run Code Online (Sandbox Code Playgroud)
@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == REQUEST_ID) {
if (PersimissionTest.verifyPermissions(grantResults)) {
Toast.makeText(mcontext, "Contacts permissions granted.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mcontext, "Contacts permissions were not granted.", Toast.LENGTH_LONG).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Run Code Online (Sandbox Code Playgroud)
以下代码检查应用程序是否具有读取用户联系人的权限,并在必要时请求权限:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// 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(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
else
{
// Permission already granted ... This is where you can continue your further business logic...
}
Run Code Online (Sandbox Code Playgroud)
以下是回调方法:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Run Code Online (Sandbox Code Playgroud)
有关详细说明,请访问此处(Android 官方页面)或此处(Tutsplus 教程):
| 归档时间: |
|
| 查看次数: |
4586 次 |
| 最近记录: |