我想为我的应用授予存储权限。我的代码工作完美,直到棉花糖,只有牛轧糖的问题
以下方法总是在牛轧糖中返回false,即使是从设置手动授予的权限。
private boolean checkWriteExternalPermission() {
String permission = "android.permission.WRITE_EXTERNAL_STORAGE";
int res = getApplicationContext().checkCallingOrSelfPermission(
permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
我将此用于Nougat并允许,但上述方法仍然返回false。
void storagePermission(){
StorageManager sm = (StorageManager)getSystemService(Context.STORAGE_SERVICE);
StorageVolume volume = sm.getPrimaryStorageVolume();
Intent intent = volume.createAccessIntent(Environment.DIRECTORY_PICTURES);
startActivityForResult(intent, 1);
}
请帮我解决这个问题。
答案 0 :(得分:0)
你应该使用libs: https://github.com/hotchemi/PermissionsDispatcher
@RuntimePermissions
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivityPermissionsDispatcher.storagePermissionWithCheck(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
void storagePermission(){
StorageManager sm =(StorageManager)getSystemService(Context.STORAGE_SERVICE);
StorageVolume volume = sm.getPrimaryStorageVolume();
Intent intent = volume.createAccessIntent(Environment.DIRECTORY_PICTURES);
startActivityForResult(intent, 1);
}
@OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
void showDeniedForCamera() {
// don't allow code here
}
@OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
void showNeverAskForCamera() {
// neverAskAgain code here
}
}
答案 1 :(得分:0)
您应该添加以下代码:
public void onActivityResult(final int requestCode, int resultCode, final Intent data){
if(requestCode==1) {
switch (resultCode) {
case Activity.RESULT_OK:
getContentResolver().takePersistableUriPermission(data.getData(),
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
break;
}
}
}