如何在点击通知时正确地打开文件

4

我正在使用 IntentService 从互联网下载文件,并在下载过程中显示一个 Notification。下载完成后,我需要能够单击通知以在适当的应用程序中打开已下载的文件。以下是我用于此目的的代码:

Intent intent = IntentUtils.getOpenFileIntent(task.getTargetFolder()
    + File.separator + task.getFileNode().getName());
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);
taskStackBuilder.addParentStack(MainActivity.class);
taskStackBuilder.addNextIntent(intent);
PendingIntent pi = taskStackBuilder.getPendingIntent(0,
    PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);

这是我创建Intent的方法:

public static Intent getOpenFileIntent(String path) {
    File file = new File(path);
    Uri uri = Uri.fromFile(file);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String extension = fileExt(path);
    String type = mime.getMimeTypeFromExtension(extension);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(uri, type);
    return intent;
}

问题在于点击通知会关闭任何当前打开的应用程序。我只需要在当前打开的应用程序上显示应用程序选择器。我认为问题在于TaskStackBuilder的使用,但没有其他方法可以创建ACTION_VIEW IntentPendingIntent实例。

尝试这个:PendingIntent contentIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_CANCEL_CURRENT) - M D
@SimplePlan 谢谢,它有效!完全忘记了这种 PendingIntent 的创建方式。如果您将您的评论添加到答案部分,我会将其标记为已接受。 - Lingviston
@Lingviston 在哪里写上述代码?请给我一些提示,以便从通知中打开下载文件。 - Rajesh
@Rajesh 在通知创建期间使用它。 - Lingviston
2个回答

3

1
文件夹可以打开,但是点击文件时,它不会打开。 有什么解决办法吗? - Rumit Patel

1
private NotificationManager manager;
private Intent notiIntent;

/// id is integre value which in unique for notifications

notiIntent= new Intent(context, CurrentActiivty.class);
            notiIntent.putExtra("id", id);
            notiIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);



Notification notification = new Notification(R.drawable.icon, "your text on notification bar", System.currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notiIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setLatestEventInfo(context,"text here", message, contentIntent);
        notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
        notiIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        manager.notify(id, notification);

现在,在调用活动中编写以下代码

Bundle extras = getIntent().getExtras();
int id= extras.getInt("id");
NotificationManager notificationManager;
            notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.cancel(id);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接