Android 6.0调用相机图册崩溃的完美解决方案
最近客户更新系统发现,以前的项目在调用相机的时候,闪退掉了,很奇怪,后来查阅后发现,Android6.0以后需要程序授权相机权限,默认会给出提示,让用户授权,个人感觉这一特性很好,大概如下:
导入AndroidV4,V7包!
AndroidStudio导入很简单,右键项目后找到dependency就ok了。
继承AppCompatActivity
publicclassMainActivityextendsAppCompatActivity
引入需要的类库
importandroid.support.design.widget.Snackbar; importandroid.support.v4.app.ActivityCompat; importandroid.support.v7.app.AppCompatActivity;
检查相机权限,并请求权限
//BEGIN_INCLUDE(camera_permission_request) if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)){ //Provideanadditionalrationaletotheuserifthepermissionwasnotgranted //andtheuserwouldbenefitfromadditionalcontextfortheuseofthepermission. //Forexampleiftheuserhaspreviouslydeniedthepermission. Log.i(TAG, "Displayingcamerapermissionrationaletoprovideadditionalcontext."); Snackbar.make(mLayout,R.string.permission_camera_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.ok,newView.OnClickListener(){ @Override publicvoidonClick(Viewview){ ActivityCompat.requestPermissions(MainActivity.this, newString[]{Manifest.permission.CAMERA}, REQUEST_CAMERA); } }) .show(); }else{ //Camerapermissionhasnotbeengrantedyet.Requestitdirectly. ActivityCompat.requestPermissions(this,newString[]{Manifest.permission.CAMERA}, REQUEST_CAMERA); } //END_INCLUDE(camera_permission_request)
授权后接收回调方法:
/** *Callbackreceivedwhenapermissionsrequesthasbeencompleted. */ @Override publicvoidonRequestPermissionsResult(intrequestCode,@NonNullString[]permissions, @NonNullint[]grantResults){ if(requestCode==REQUEST_CAMERA){ //BEGIN_INCLUDE(permission_result) //Receivedpermissionresultforcamerapermission. Log.i(TAG,"ReceivedresponseforCamerapermissionrequest."); //Checkiftheonlyrequiredpermissionhasbeengranted } }
混合应用开发解决方案
对于混合应用开发,有两种解决方案:
更改现有插件,添加权限访问代码(可能有有些麻烦)
调用权限插件:
安装:
cordovapluginaddcordova-plugin-android-permissions@0.10.0
包含的权限
//Example permissions.ACCESS_COARSE_LOCATION permissions.CAMERA permissions.GET_ACCOUNTS permissions.READ_CONTACTS permissions.READ_CALENDAR ...
示例代码
varpermissions=cordova.plugins.permissions; permissions.hasPermission(permissions.CAMERA,checkPermissionCallback,null); functioncheckPermissionCallback(status){ if(!status.hasPermission){ varerrorCallback=function(){ console.warn('Camerapermissionisnotturnedon'); } permissions.requestPermission( permissions.CAMERA, function(status){ if(!status.hasPermission)errorCallback(); }, errorCallback); } }
以上所述是小编给大家介绍的Android6.0调用相机图册崩溃的完美解决方案,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!