1. 程式人生 > >Android Fail to connect to camera service, location provider requires ACCESS_COARSE_LOCATION permiss

Android Fail to connect to camera service, location provider requires ACCESS_COARSE_LOCATION permiss

升級過gradle後執行應用發現拍照和定位功能不能用了,檢視log日誌重點的錯誤資訊分別如下:

java.lang.RuntimeException: Fail to connect to camera service
location provider requires ACCESS_COARSE_LOCATION permission.

 兩個解決方式

1 將gradle中編譯SDK改為22以下。自Android6.0後系統加強了隱私保護,只是在清單檔案新增許可權申請前提下還得要動態獲取許可權。

2 動態獲取許可權

定位:

private static final int MY_PERMISSION_LOCATION = 255;//0-255
private void gpsPremissionCheck() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
				&& this.checkSelfPermission(
				Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
				&& this.checkSelfPermission(
				Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
			requestPermissions(
					new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
							Manifest.permission.ACCESS_FINE_LOCATION},
					MY_PERMISSION_LOCATION);
		} else {
			//SDK編譯版本低於22,直接執行
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode == MY_PERMISSION_LOCATION
				&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
			//申請許可權成功,do some thing you want.
		}else {
			//finish();
		}
	}

拍照:


/** 獲取許可權*/
	private void getPermission() {
		if (Build.VERSION.SDK_INT>22){
			if (ContextCompat.checkSelfPermission(this,
					android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
				//先判斷有沒有許可權 ,沒有就在這裡進行許可權的申請
				ActivityCompat.requestPermissions(this,
						new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},CAMERA_OK);
			}else {
				//說明已經獲取到攝像頭許可權了
			}
		}else {
			Log.i("MainActivity","這個說明系統版本在6.0之下,不需要動態獲取許可權。");
		}
	}