0

Android23以上动态鉴权实现的方法及思路

直接上代码了,主要使用到onRequestPermissionsResult、requestPermissions和checkSelfPermission 方法

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
scanIntent();
} else {
// Permission Denied
Toast.makeText(getActivity(), “您拒绝了权限(请到设置中设置权限)”, Toast.LENGTH_SHORT)
.show();
}
break;
case 300:
test2();
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

public void checkPermission() {

if (Build.VERSION.SDK_INT >= 23) {
// int write = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
// int read = getActivity().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
int write = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE);
int read = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_EXTERNAL_STORAGE);
if (write != PackageManager.PERMISSION_GRANTED || read != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 300);
} else {
test2();
}
} else {
test2();
}
}

private void test2(){
StringBuffer stringBuffer = new StringBuffer(Environment.getExternalStorageDirectory().getAbsolutePath());
// StringBuffer stringBuffer = new StringBuffer(getActivity().getExternalFilesDir(null).getAbsolutePath());
stringBuffer.append(“/export/”);
String str= stringBuffer.toString();
Log.e(“STATE”, Environment.getExternalStorageState());
Log.e(“STATE”, getActivity().getExternalFilesDir(null).getAbsolutePath());
Log.e(“STATE”, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
LocalDBManagerTools localDBManagerTools = new LocalDBManagerTools();
localDBManagerTools.exportAllDatabases(str,getActivity());
LocalSharedPreferencesManagerTools localSharedPreferencesManagerTools = new LocalSharedPreferencesManagerTools();
localSharedPreferencesManagerTools.exportAllSharedPrefrerences(str,getActivity());
}

天边的星星