问题描述: 在Android应用中使用DownloadManager下载了一个csv文件,但是无法打开该文件。
解决方法:
public class DownloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (downloadId != -1) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(columnIndex)) {
String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
if (uriString != null) {
Uri uri = Uri.parse(uriString);
String filePath = uri.getPath(); // 获取文件路径
if (filePath != null && filePath.endsWith(".csv")) {
openCsvFile(context, uri);
}
}
}
}
cursor.close();
}
}
private void openCsvFile(Context context, Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/csv");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "无法打开csv文件", Toast.LENGTH_SHORT).show();
}
}
}
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(csvFileUrl));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.csv");
long downloadId = downloadManager.enqueue(request);
这样,当文件下载完成后,会触发DownloadCompleteReceiver中的广播接收器,然后打开下载的csv文件。