【发布时间】:2012-08-19 22:18:48
【问题描述】:
我开发了一个应用程序来下载视频文件并将其存储在 SD 卡中。在此过程中,我还使用NotificationManager 将下载的进度和状态更新为状态栏通知。
我的类名为DownloadTask.java 扩展了AsyncTask。所以在这里我使用onProgressUpdate() 方法更新进度,其中我使用NotificationManager 来达到目的。一切都像一个魅力,除了下载完成后我想点击通知打开特定的视频文件。所以这就是我所做的:
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.stat_sys_download_done;
long when = System.currentTimeMillis();
mNotification = new Notification(icon, "", when);
mContentTitle_complete = mContext.getString(R.string.download_complete);
notificationIntent = new Intent(mContext,OpenDownloadedVideo.class);
notificationIntent.putExtra("fileName", file);
mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
mNotification.setLatestEventInfo(mContext, file, mContentTitle_complete, mContentIntent);
mNotification.flags = Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
请注意,fileName 和 NOTIFICATION_ID 在我的情况下是独一无二的。
ActivityOpenDownloadedVideo.java 通过以下方式打开文件:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
fileName = getIntent().getExtras().getString("fileName");
Intent i = new Intent(Intent.ACTION_VIEW);
File videoFileToPlay = new File(Environment.getExternalStorageDirectory()+"/MyFolder"+"/"+fileName);
i.setDataAndType(Uri.fromFile(videoFileToPlay), "video/*");
startActivity(i);
finish();
} catch(Exception e) {
//
}
}
因此,当我第一次下载视频并单击通知时,将打开相应的视频文件。但是下次我下载另一个视频时,点击通知,下载的第一个文件将再次打开。
这是因为 getIntent 内的 OpenDownloadedVideo 返回第一个创建的 Intent 而不是最新的。我该如何纠正这个问题?
另外,请注意,当我下载多个视频时存在问题场景,例如如果我下载了五个不同的视频文件并且状态栏中有五个通知。每次点击通知都会打开同一个文件。
【问题讨论】:
标签: android android-intent notifications android-activity