开发一个相机应用,需要申请三个权限:相机、读文件、写文件。文章来源:https://www.toymoban.com/news/detail-504465.html
1、在AndroidManifest.xml中添加
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2、新建一个Permission类
public class Permission {
public static final int REQUEST_CODE = 5;
//定义三个权限
private static final String[] permission = new String[]{
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
//每个权限是否已授
public static boolean isPermissionGranted(Activity activity){
if(Build.VERSION.SDK_INT >= 23){
for(int i = 0; i < permission.length;i++) {
int checkPermission = ContextCompat.checkSelfPermission(activity,permission[i]);
/***
* checkPermission返回两个值
* 有权限: PackageManager.PERMISSION_GRANTED
* 无权限: PackageManager.PERMISSION_DENIED
*/
if(checkPermission != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}else{
return true;
}
}
public static boolean checkPermission(Activity activity){
if(isPermissionGranted(activity)) {
return true;
} else {
//如果没有设置过权限许可,则弹出系统的授权窗口
ActivityCompat.requestPermissions(activity,permission,REQUEST_CODE);
return false;
}
}
}
3、在MainActivity中加入授权操作
@Override
protected void onStart() {
super.onStart();
Permission.checkPermission(this);
}
@Override
protected void onResume() {
super.onResume();
if(Permission.isPermissionGranted(this)) {
Log.i("PERMISSION","请求权限成功");
}
}
初步授权成功文章来源地址https://www.toymoban.com/news/detail-504465.html
4、在MainActivity中处理授权失败结果,拒绝授权则退出应用
@Override
public void onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == Permission.REQUEST_CODE) {
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED) {
Log.e("Permission","授权失败!");
// 授权失败,退出应用
this.finish();
return;
}
}
}
}
效果图
到了这里,关于Android申请权限(相机权限和读写权限)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!