首页 > 解决方案 > 下载新文件后尝试显示系统通知时应用程序崩溃

问题描述

我有一个 android 应用程序,它使用以下代码从后端服务下载 pdf 文档,在实现 android.os.AsyncTask 的类中执行,该类在后台运行:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
    String path = Environment.DIRECTORY_DOWNLOADS;
    ContentValues contentValues = new ContentValues();
    contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, file.getName());
    contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH,path);
    ContentResolver resolver = context.getContentResolver();
    Uri uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
    try {
        OutputStream os = resolver.openOutputStream(uri);
        byte data[] = new byte[4096];
        int count;
        while ((count = is.read(data)) != -1) {
            os.write(data, 0, count);
        }
        os.flush();
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
    } catch (FileNotFoundException e) {
        Log.e("DOWNLOAD","File not found",e);
    } catch (IOException e) {
        Log.e("DOWNLOAD","Error downloading file",e);
    }
} else {
    OutputStream output = new FileOutputStream(file);
    byte data[] = new byte[4096];
    int count;
    while ((count = is.read(data)) != -1) {
        output.write(data, 0, count);
    }
    IOUtils.closeQuietly(output);
    IOUtils.closeQuietly(is);
}

文件下载完成后,没有错误,我尝试在系统栏中显示通知,并在 AsyncTask 的 onPostExecute() 方法中使用以下代码:

Uri fileUri = FileProvider.getUriForFile(context,
        context.getResources().getString(R.string.file_provider_authority),
        file);

Intent viewFileIntent = new Intent(Intent.ACTION_VIEW);
viewFileIntent.setDataAndType(fileUri, mimeType);
viewFileIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
manager.addCompletedDownload(fileName, fileName, true, mimeType, file.toString(), file.length(), true);

if ( context.getPackageManager().queryIntentActivities(
        viewFileIntent,
        PackageManager.MATCH_DEFAULT_ONLY).size() > 0 ) {
    context.startActivity(viewFileIntent);
} else {
    DSSErrorUtils.showI18n(context, context.getString(R.string.MESSAGE_NO_APP_FOR_FILE));
}

当我使用Android 10 - SDK Version 30运行模拟器时,应用程序崩溃并出现以下错误(在方法 manager.addCompletedDownload() 中生成):

java.lang.SecurityException:没有写入/storage/emulated/0/Download/document_704.pdf的权限:用户10148和当前进程都没有android.permission.WRITE_EXTERNAL_STORAGE

在模拟器或具有 Android 11 - SDK 版本 30 的设备上执行的相同代码运行没有问题。对于 Android 版本 < 10,它也可以正常工作。

任何帮助将不胜感激!谢谢!

标签: androidandroid-studiocrashandroid-notificationsandroid-securityexception

解决方案


推荐阅读