【问题标题】:Android : use of mediaStore with pdf fileAndroid:使用带有 pdf 文件的 mediaStore
【发布时间】:2020-11-24 11:06:05
【问题描述】:

我尝试使用媒体存储来存储来自专用网络的 pdf 下载(在 Environment.DIRECTORY_DOWNLOADS 中)并显示它。我希望用户能够选择应用程序来显示它。 在我的代码中,我很难定义文件路径“dataFile” 可以给点建议吗,谢谢 洛朗

    String fileType="application/pdf";
    String filetxt="Choose pdf Application";
    final Intent intent = new Intent(Intent.ACTION_VIEW)
            .setDataAndType(dataFile, fileType);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Intent intentChooser = Intent.createChooser(intent,filetxt);
    context.startActivity(intentChooser);

【问题讨论】:

  • 先说说你是怎么下载文件的。您将使用或拥有一个 uri。使用那个。使用媒体存储 uri。
  • try to use media store to store a pdf download 在使用 ACTION_VIEW 之前,请务必先解决这个问题。说出你已经拥有的东西。

标签: android download mediastore


【解决方案1】:

dataFile 应该是URI,可以从File(或其路径)轻松创建

File file = new File(pathToFile);
Uri dataFile = Uri.parse(file.toString()); // or strightly pass pathToFile here

【讨论】:

  • 我使用 mediaStore 中的 DIRECTORY_DOWNLOADS
  • File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File file = new File(path, fileName);
  • 不是 mediaStore,getExternalStoragePublicDirectory 在 API 29 中已弃用
  • 所以你的目录是MediaStore.Downloads.EXTERNAL_CONTENT_URI,使用ContentResolver创建你的文件URI,就像HERE一样
【解决方案2】:

经过多次测试我的解决方案:

   String[] projections = new String[]{
                    MediaStore.DownloadColumns._ID,
                };
   String selection =MediaStore.Files.FileColumns.DISPLAY_NAME+"=?";
   String[] selectionArgs = new String[]{newLocalpath};
   Cursor cursor = context.getContentResolver().query(
                        MediaStore.Downloads.EXTERNAL_CONTENT_URI,
                        projections,
                        selection,
                        selectionArgs,
                        null
                );
   Uri uri=null;
   int docIndex = cursor.getColumnIndexOrThrow(MediaStore.DownloadColumns._ID);
   if (cursor.moveToNext()==true) {
      uri = ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, cursor.getInt(docIndex));
   }
   if (uri!=null) {
      try {
         String fileType="application/pdf";
         String filetxt="Choose pdf Application";
         final Intent intent = new Intent(Intent.ACTION_VIEW)
                                .setDataAndType(uri, fileType);
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         Intent intentChooser = Intent.createChooser(intent,filetxt);
         intentChooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intentChooser);
      } catch (Exception e) {
         Log.d("application", "error starting download file: " + e.toString());
      }

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多