Open file from notification

2019-08-12 02:58发布

问题:

I download a file from a server. For this action I'm showing a notification with indeterminate progress. When the file will be downloaded I want to open it with a click on the notification.

I get the extension and try to open it with intent like this

public static Intent openFile(Context context, File file) {
    String fileName = file.getName();

    String extension = fileName.substring(fileName.lastIndexOf(".") + 1);


    String type = "application/" + extension;

    if (getAttachmentType(fileName) == AttachmentType.IMAGE) {
        type = "image/*";
    } else if (getAttachmentType(fileName) == AttachmentType.AUDIO) {
        type = "audio/*";
    } else if (getAttachmentType(fileName) == AttachmentType.VIDEO) {
        type = "video/*";
    } else if (getAttachmentType(fileName) == AttachmentType.WORD) {
        type = "application/msword";
    } else if (getAttachmentType(fileName) == AttachmentType.EXCEL) {
        type = "application/vnd.ms-excel";
    } else if (getAttachmentType(fileName) == AttachmentType.POWERPOINT) {
        type = "application/vnd.ms-powerpoint";
    } else if (getAttachmentType(fileName) == AttachmentType.TXT) {
        type = "text/*";
    }

    Uri path = Uri.fromFile(file);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Intent chooser = Intent.createChooser(intent, context.getResources().getString(R.string.open_file_with));
    intent.setDataAndType(path, type);
    return chooser;
}

And on the notification do this

Intent intent = ActionsHelper.openFile(context, file);
if (intent != null) {
     PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
      mBuilder.setContentIntent(pendingIntent);
}

My problem is that with any extension the message on the chooser is No app can perform this action. Am I missing something?

回答1:

Ok I found it. I replace

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

with

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

and it worked



回答2:

You are setting the Intent data and type after creating the chooser Intent. Switch it to:

Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, type);

Intent chooser = Intent.createChooser(intent, context.getResources().getString(R.string.open_file_with));