对于API为23或更高版本的Android设备,如何在不重新启动应用的情况下授予外部存储权限(有点像用户的音乐库在单个会话中上传到Google Play音乐)?我知道这个问题已经在SO中多次得到解决,但到目前为止我没有找到任何运气。
以下是我的清单文件中的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // API 23
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return; // Included here to prevent the app from crashing.
}
}
/**
* CODE HERE FOR INSTANTIATIONS AND SUCH.
*/
}
...因为截至目前,我需要重新启动应用以获取权限(以及MainActivity的实例化等) 接受初始弹出窗口的权限。
非常感谢。
答案 0 :(得分:1)
正如@CommonsWare建议的那样,你可以将所有 INSTANTIATIONS AND SUCH 的代码放在像instantiateMyObjects()
这样的方法中,并在onCreate()
中调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // API 23
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_CODE);
// Define the constant MY_PERMISSION_CODE.
return; // Included here to prevent the app from crashing.
}
}
instantiateMyObjects();
}
当用户接受/拒绝您的权限请求时,onRequestPermissionsResult()
被调用。不要忘记定义MY_PERMISSION_CODE
将其视为1
。
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now you can instantiate your objects.
instantiateMyObjects();
} else {
// User denied it.
}
}
}