Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 6.0調用相機圖冊崩潰的完美解決方案

Android 6.0調用相機圖冊崩潰的完美解決方案

編輯:關於Android編程

最近客戶更新系統發現,以前的項目在調用相機的時候,閃退掉了,很奇怪,後來查閱後發現,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 [email protected]

包含的權限

// 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調用相機圖冊崩潰的完美解決方案,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對本站網站的支持!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved