我试图在运行时请求用户权限. API是23,我想从手机的图库中提取图像.下面是一些片段,这是我到目前为止的代码:
在Activity的onCreate()中检查:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED) {
imageUploader5.setEnabled(true);
ActivityCompat.requestPermissions(this, new String[]
{ Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
然后我覆盖:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
imageUploader5.setEnabled(true);
}
}
}
但我还是无法让应用程序在AVD上运行.
编辑:清单中的权限:
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.READ_EXTERNAL_STORAGE" />
解决方法:
根据您构建if状态的方式,只有在已经授予用户权限的情况下才会要求用户权限.添加其他如下:
// Enable if permission granted
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED) {
imageUploader5.setEnabled(true);
}
// Else ask for permission
else {
ActivityCompat.requestPermissions(this, new String[]
{ Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
编辑
在清单中概括您的用户权限,以便它可以被不同的和未来的API级别使用:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />