欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 6.0调用相机图册崩溃的完美解决方案

程序员文章站 2024-03-05 23:40:07
最近客户更新系统发现,以前的项目在调用相机的时候,闪退掉了,很奇怪,后来查阅后发现,android 6.0以后需要程序授权相机权限,默认会给出提示,让用户授权,个人感觉这一...

最近客户更新系统发现,以前的项目在调用相机的时候,闪退掉了,很奇怪,后来查阅后发现,android 6.0以后需要程序授权相机权限,默认会给出提示,让用户授权,个人感觉这一特性很好,大概如下:

导入android v4, v7包!

android studio 导入很简单,右键项目后找到dependency就ok了。

继承appcompatactivity

public class mainactivity extends appcompatactivity

引入需要的类库

import android.support.design.widget.snackbar;
import android.support.v4.app.activitycompat;
import android.support.v7.app.appcompatactivity;

检查相机权限,并请求权限

// begin_include(camera_permission_request)
if (activitycompat.shouldshowrequestpermissionrationale(this,
manifest.permission.camera)) {
// provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// for example if the user has previously denied the permission.
log.i(tag,
"displaying camera permission rationale to provide additional context.");
snackbar.make(mlayout, r.string.permission_camera_rationale,
snackbar.length_indefinite)
.setaction(r.string.ok, new view.onclicklistener() {
@override
public void onclick(view view) {
activitycompat.requestpermissions(mainactivity.this,
new string[]{manifest.permission.camera},
request_camera);
}
})
.show();
} else {
// camera permission has not been granted yet. request it directly.
activitycompat.requestpermissions(this, new string[]{manifest.permission.camera},
request_camera);
}
// end_include(camera_permission_request)

授权后接收回调方法:

/**
* callback received when a permissions request has been completed.
*/
@override
public void onrequestpermissionsresult(int requestcode, @nonnull string[] permissions,
@nonnull int[] grantresults) {
if (requestcode == request_camera) {
// begin_include(permission_result)
// received permission result for camera permission.
log.i(tag, "received response for camera permission request.");
// check if the only required permission has been granted
} 
}

混合应用开发解决方案

对于混合应用开发,有两种解决方案:

更改现有插件,添加权限访问代码(可能有有些麻烦)

调用权限插件:

安装:

cordova plugin add cordova-plugin-android-permissions@0.10.0

包含的权限

// example 
permissions.access_coarse_location
permissions.camera
permissions.get_accounts
permissions.read_contacts
permissions.read_calendar
...

示例代码

var permissions = cordova.plugins.permissions;
permissions.haspermission(permissions.camera, checkpermissioncallback, null);
function checkpermissioncallback(status) {
if(!status.haspermission) {
var errorcallback = function() {
console.warn('camera permission is not turned on');
}
permissions.requestpermission(
permissions.camera,
function(status) {
if(!status.haspermission) errorcallback();
},
errorcallback);
}
}

以上所述是小编给大家介绍的android 6.0调用相机图册崩溃的完美解决方案,希望对大家有所帮助