android开发权限询问的示例代码
现在基于信息安全问题,特别是版本是23以上权限越严格。
特别是拍照,读,写权限
一般权限允许过,下次就不用询问了的,所以很多应用都喜欢在首页或者启动页直接询问,不允许的就用不了1、下面给出封装好的类,至于什么时候调看项目需要
publicclassEasyPermissions{ privatestaticfinalStringTAG="EasyPermissions"; publicinterfacePermissionCallbacksextends ActivityCompat.OnRequestPermissionsResultCallback{ voidonPermissionsGranted(Listperms); voidonPermissionsDenied(List perms); } /** *Checkifthecallingcontexthasasetofpermissions. * *@paramcontextthecallingcontext. *@parampermsoneoremorepermissions,suchas{@codeandroid.Manifest.permission.CAMERA}. *@returntrueifallpermissionsarealreadygranted,falseifatleastonepermission *isnotyetgranted. */ publicstaticbooleanhasPermissions(Contextcontext,String...perms){ for(Stringperm:perms){ booleanhasPerm=(ContextCompat.checkSelfPermission(context,perm)==PackageManager.PERMISSION_GRANTED); if(!hasPerm){ returnfalse; } } returntrue; } /** *Requestasetofpermissions,showingrationaleifthesystemrequestsit. * *@paramobjectActivityorFragmentrequestingpermissions.Shouldimplement *{@linkActivityCompat.OnRequestPermissionsResultCallback} *or *{@linkandroid.support.v13.app.FragmentCompat.OnRequestPermissionsResultCallback} *@paramrationaleamessageexplainingwhytheapplicationneedsthissetofpermissions,will *bedisplayediftheuserrejectstherequestthefirsttime. *@paramrequestCoderequestcodetotrackthisrequest,mustbe<256. *@parampermsasetofpermissionstoberequested. */ publicstaticvoidrequestPermissions(finalObjectobject,Stringrationale, finalintrequestCode,finalString...perms){ requestPermissions(object,rationale, android.R.string.ok, android.R.string.cancel, requestCode,perms); } /** *Requestasetofpermissions,showingrationaleifthesystemrequestsit. * *@paramobjectActivityorFragmentrequestingpermissions.Shouldimplement *{@linkActivityCompat.OnRequestPermissionsResultCallback} *or *{@linkandroid.support.v13.app.FragmentCompat.OnRequestPermissionsResultCallback} *@paramrationaleamessageexplainingwhytheapplicationneedsthissetofpermissions,will *bedisplayediftheuserrejectstherequestthefirsttime. *@parampositiveButtoncustomtextforpositivebutton *@paramnegativeButtoncustomtextfornegativebutton *@paramrequestCoderequestcodetotrackthisrequest,mustbe<256. *@parampermsasetofpermissionstoberequested. */ publicstaticvoidrequestPermissions(finalObjectobject,Stringrationale, @StringResintpositiveButton, @StringResintnegativeButton, finalintrequestCode,finalString...perms){ checkCallingObjectSuitability(object); booleanshouldShowRationale=false; for(Stringperm:perms){ shouldShowRationale=shouldShowRationale||shouldShowRequestPermissionRationale(object,perm); } if(shouldShowRationale){ //弹框询问 AlertDialogdialog=newAlertDialog.Builder(getActivity(object)) .setMessage(rationale) .setPositiveButton(positiveButton,newDialogInterface.OnClickListener(){ @Override publicvoidonClick(DialogInterfacedialog,intwhich){ executePermissionsRequest(object,perms,requestCode); } }) .setNegativeButton(negativeButton,newDialogInterface.OnClickListener(){ @Override publicvoidonClick(DialogInterfacedialog,intwhich){ //Donothing,userdoesnotwanttorequest PermissionCallbackscallbacks=(PermissionCallbacks)object; if(callbacks!=null){ callbacks.onPermissionsDenied(newArrayList ()); } } }).create(); dialog.show(); }else{ executePermissionsRequest(object,perms,requestCode); } } /** *Handletheresultofapermissionrequest,shouldbecalledfromthecallingActivity's *{@linkActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int,String[],int[])} *method. * *Ifanypermissionsweregrantedordenied,theActivitywillreceivetheappropriate *callbacksthrough{@linkPermissionCallbacks}andmethodsannotatedwith *{@linkAfterPermissionGranted}willberunifappropriate. * *@paramrequestCoderequestCodeargumenttopermissionresultcallback. *@parampermissionspermissionsargumenttopermissionresultcallback. *@paramgrantResultsgrantResultsargumenttopermissionresultcallback. *@paramobjectthecallingActivityorFragment. *@throwsIllegalArgumentExceptionifthecallingActivitydoesnotimplement *{@linkPermissionCallbacks}. */ publicstaticvoidonRequestPermissionsResult(intrequestCode,String[]permissions, int[]grantResults,Objectobject){ checkCallingObjectSuitability(object); PermissionCallbackscallbacks=(PermissionCallbacks)object; //Makeacollectionofgrantedanddeniedpermissionsfromtherequest. ArrayList granted=newArrayList<>(); ArrayList denied=newArrayList<>(); for(inti=0;i 0){ thrownewRuntimeException("Cannotexecutenon-voidmethod"+method.getName()); } try{ //Makemethodaccessibleifprivate if(!method.isAccessible()){ method.setAccessible(true); } method.invoke(object); }catch(IllegalAccessExceptione){ ILogger.e(TAG,"runDefaultMethod:IllegalAccessException",e); }catch(InvocationTargetExceptione){ ILogger.e(TAG,"runDefaultMethod:InvocationTargetException",e); } } } } } privatestaticvoidcheckCallingObjectSuitability(Objectobject){ //MakesureObjectisanActivityorFragment if(!((objectinstanceofFragment)||(objectinstanceofActivity))){ thrownewIllegalArgumentException("CallermustbeanActivityoraFragment."); } //MakesureObjectimplementscallbacks if(!(objectinstanceofPermissionCallbacks)){ thrownewIllegalArgumentException("CallermustimplementPermissionCallbacks."); } }}
注:这个类不是我写的,分享给大家
2、调用示例(activity或fragment):(方法调用的时机随你)
privatevoidrequestGalleryPermission(){ //权限参数可以添加很多,不固定参数的 if(EasyPermissions.hasPermissions(this,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE)){ getPhotos();//如果具有权限做的操作 }else{ //Askforonepermission EasyPermissions.requestPermissions(this,getString(R.string.permissions_tips_gallery), GalleryFinal.PERMISSIONS_CODE_GALLERY,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE); } }
3、拒绝和允许做的操作(activity或fragment):
@Override publicvoidonPermissionsGranted(Listlist){ //允许 getPhotos(); } @Override publicvoidonPermissionsDenied(List list){ //拒绝 mTvEmptyView.setText(R.string.permissions_denied_tips); //mIvTakePhoto.setVisibility(View.GONE); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。