java - 在继续之前检查是否授予了在存储上写入的权限

标签 java android

我的应用程序出现问题。要使用选项,我需要授予外部存储访问权限。我在那里找到了完美的代码:

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;
}

}

来源:Storage permission error in Marshmallow

问题是,代码工作正常,但我不明白如果未授予访问权限(或等待用户单击“允许”,然后再继续我的代码),如何阻止我自己的代码继续。

我的代码:

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())

关于java - 在继续之前检查是否授予了在存储上写入的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58580334/

相关文章:

java - 如何使用tomcat native(version 8.5.x)服务静态文件上传下载?

groovy - Griffon SystemTray 中的自动更新(时间)工具提示

android - sencha touch native 应用程序是否有可能仍在后台运行?

android - 在 Android 应用程序中创建 MS Word 文档

android - 是什么杀死了 Android AsyncTask?

java - java中构造函数返回值有什么用以及如何访问这个值?

java - 在写入文件之前格式化 JSON

java - 如何将 HttpServletRequest 对象中包含的所有参数(名称和值)表示为单个字符串?

android - Qt移动视频通话流

java - keystore 密码被篡改