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

时间:2014-03-21 09:06:14

标签: android notifications

我使用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用法中,但没有其他方法可以为PendingIntent ACTION_VIEW创建Intent个实例。

2 个答案:

答案 0 :(得分:3)

您需要创建PendingIntent并设置为Notification

PendingIntent contentIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_CANCEL_CURRENT)

有关更多信息,请转至http://developer.android.com/guide/topics/ui/notifiers/notifications.html

答案 1 :(得分: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);