Kat*_*hil 18 android android-permissions
我想知道当用户按下"允许"按钮进行联系方式访问/日历访问等时,我们是否有办法识别事件,
我知道有一种方法可以通过ActivityCompat.requestPermissions请求权限,但有没有办法在用户授予权限后立即执行操作?
raf*_*007 29
首先定义变量:
public static int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
Run Code Online (Sandbox Code Playgroud)
请求权限使用:
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation 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.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
Run Code Online (Sandbox Code Playgroud)
现在使用以下方法捕获结果
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION : {
// 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.
Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Run Code Online (Sandbox Code Playgroud)
对于碎片
如果您在a中尝试此代码fragment,请更改
checkSelfPermission()
至
ActivityCompact.checkSelfPermission()
而且还改变了
ActivityCompat.requestPermissions()
至
requestPermissions()
许可结果的处理(允许或拒绝)与活动相同.
有关更完整的示例,请参阅此答案
| 归档时间: |
|
| 查看次数: |
19604 次 |
| 最近记录: |