我正在测试我的应用程序,运行在
Marshmallow 6.0
上,但是它由于缺少android.permission.READ_EXTERNAL_STORAGE
权限而被强制关闭。即使该权限已在清单文件中定义。我在某个地方读到,如果我在运行时请求权限,则不会强制关闭您的应用程序。我也阅读过这篇安卓文档,其中提供了请求运行时权限的方法。
所以,我知道我们可以按照安卓文档中所述的方式请求权限,如下:
// 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.
}
}
上述代码有一个回调方法 onRequestPermissionsResult
,它获取结果。
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
}
}
我的问题是在哪里向用户请求权限?我们应该在应用程序开始时请求权限,还是在需要权限时才这样做?
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
。 - Pararth