android 6.0 新權限管理方式對sdcard讀取的設計方法
android 6.0 採對個別app的權限管理方式, 如果使用者未開放權限, 則app訪問sdcard的功能將出問題
所以如果使用者未開放權限的話, 可在app中要求使用者開放
在activity中的oncreate寫如下程式碼:
boolean hasPermission = (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
上面的程式碼, 會引發以下事件
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//如果同意, 則重啟acitvity, 正常執行
recreate();
} else {
//如果不同意, 則再次請求, 若使用者同意考慮, 則再重啟activity, 會再訽問一次
TextApp.YesNoListener ynListener=new TextApp.YesNoListener() {
@Override
public void onYes() {
recreate();
}
//若不同意再考慮, 則退出程序
@Override
public void onNo() {
finish();
}
};
TextApp.showOkCancelDialog("The app was not allowed to write to your storage. Hence, it cannot function properly. Do you want to consider granting it this permission again?",this,ynListener);
}
}
}
}
TextApp中顯示訽問視窗的函數
public static void showOkCancelDialog(String msg, Context _ac,
YesNoListener _yesnoListener) {
final YesNoListener yesnoListener = _yesnoListener;
AlertDialog.Builder ssa = new AlertDialog.Builder(_ac);
ssa.setMessage(msg);
ssa.setIcon(R.drawable.ic_noti_dict);
ssa.setPositiveButton(
getContext().getResources().getString(R.string.strOk),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
yesnoListener.onYes();
}
}).setNegativeButton(
getContext().getResources().getString(R.string.strCancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.out.println("cancel");
yesnoListener.onNo();
// AnswerIsOK = false; }
});
AlertDialog alert = ssa.create();
alert.show();
}