您好我已将文件从网址保存到我的文件目录。并设置广播恢复以检测下载何时完成,然后触发action_view意图以选择打开它的应用程序。这一切都正常但当我选择另一个应用程序时它无法显示该文件。如果我从通知中心选择文件,它打开正常,所以它肯定会下载加载到文件目录,但不知道为什么它会从我的应用程序打开时加载。
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(filename);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
ContextWrapper c = new ContextWrapper(getBaseContext());
final String filePath = c.getFilesDir().getPath() + "/";
Log.v("Search", "filePath = " + filePath);
request.setDestinationInExternalFilesDir(getBaseContext(), filePath, filename);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
Toast.makeText(getBaseContext(), "Downloading...", Toast.LENGTH_LONG).show();
BroadcastReceiver onComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String path = getFilesDir().getPath() +"/" + filename;
File f = new File(path);
Log.v("Search", "path = " + path);
String fileExt = Global.getFileExt(filename);
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(fileExt);
newIntent.setDataAndType(Uri.fromFile(f), mimeType);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(newIntent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(context, "No handler for this type of file.", 4000).show();
}
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}