java - 在继续之前检查是否授予了写入存储的权限
问题描述
我的应用程序有问题。要使用某个选项,我需要授予外部存储访问权限。我在那里找到了完美的代码:
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
来源:棉花糖中的存储权限错误
问题是,代码运行良好,但我不明白如果未授予访问权限(或等待用户在继续我的代码之前单击“允许”),如何阻止我自己的代码继续运行。
我的代码:
isStoragePermissionGranted();
File outputFile = new File("");
InputStream is = getResources().openRawResource(((Sound) adapter.getItem(index)).getMpsound());
try {
byte[] buffer = new byte[is.available()];
is.read(buffer);
File outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
outputFile = new File(outputDir, getResources().getResourceEntryName(((Sound) adapter.getItem(index)).getMpsound()) + ".mp3");
OutputStream os = new FileOutputStream(outputFile);
os.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", outputFile));
share.putExtra(Intent.EXTRA_TEXT, "\"" + ((Sound) adapter.getItem(index)).getTitre_show() + "\" shared by my app !");
startActivity(Intent.createChooser(share, "Share Sound File"));
return true;
目前,一切都已执行,应用程序会尝试共享文件,即使访问权限未被授予。所以它不起作用。如果我回去,要求允许访问的弹出窗口就在那里,等待答案。
我怎样才能做到这一点?
解决方案
更改此行
isStoragePermissionGranted();
进入这个应该工作。
if(isStoragePermissionGranted())
推荐阅读
- paypal - PayPal 辅助帐户创建无效的 client_id 或 redirect_uri
- android-studio - 安装后无法打开 Android Studio
- python - 使用单个元素或列表作为值构建字典
- arrays - 如何按值对打字稿中的数组进行排序
- postgresql - 使用 postgres 存储后端时,Vault 报告缺少客户端令牌
- python - 使用 python 请求获取网站登录的同意 cookie (CMP euconsent-v2)
- unit-testing - 单元测试 FastAPI CRUD 无法按预期工作
- python - 用户输入只能是字母字符并包含空格
- laravel - 如何更改 spatie 标签 slug 生成器方法
- c# - 从 dmcmnutils.dll 读取带参数的导出函数