安卓系统:使用带有pdf文件的mediaStore



我尝试使用媒体存储来存储从专用网络下载的pdf文件(在Environment.DDIRECTORY_DOWNLOADS中(并显示它。我希望用户能够选择显示它的应用程序。在我的代码中,我很难定义文件路径";数据文件";你能给我建议吗,谢谢Laurent

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

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

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

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

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

最新更新