Android 6.0 后動(dòng)態(tài)申請(qǐng)權(quán)限注意點(diǎn)

1.必須在Manifest文件中靜態(tài)注冊(cè)
2.動(dòng)態(tài)申請(qǐng)
if (ContextCompat.checkSelfPermission(this , Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
// 當(dāng)?shù)谝淮蜗蛴脩羯暾?qǐng)權(quán)限被拒絕了,這個(gè)才會(huì)返回true 用于向用戶解釋為什么需要這個(gè)權(quán)限 if(ActivityCompat.shouldShowRequestPermissionRationale(this , Manifest.permission.CAMERA)) {
new AlertDialog.Builder(this).setMessage(R.string.granted_camera).setPositiveButton("確定", new DialogInterface.OnClickListener()
{ @Override public void onClick(DialogInterface dialog, int which) { // 申請(qǐng)相機(jī)權(quán)限 ActivityCompat.requestPermissions(MainActivity.this , new String[]{Manifest.permission.CAMERA} , CAMERA_REQUEST_CODE); } }).show(); } else { ActivityCompat.requestPermissions(this , new String[]{Manifest.permission.CAMERA} , ````CAMERA_REQUEST_CODE); } } else { mTextView.setTextColor(Color.GREEN); mTextView.setText("相機(jī)權(quán)限已經(jīng)獲取"); } }}

3.獲取權(quán)限回調(diào)
@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_REQUEST_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { mTextView.setTextColor(Color.GREEN); mTextView.setText(R.string.granted_camera); } else { if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { Toast.makeText(this, R.string.deny_camera , Toast.LENGTH_SHORT).show(); } } }}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容