最近客户更新系统发现,以前的项目在调用相机的时候,闪退掉了,很奇怪,后来查阅后发现,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调用相机图册崩溃的完美解决方案,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!