Notification pressed to open up file in default app (android)

android, android-intent, android-notifications, notifications

Solution

Create the notification like this with the pending intent to open the default audio player

    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_VIEW);
    File file = new File("YOUR_SONG_URI"); // set your audio path 
    intent.setDataAndType(Uri.fromFile(file), "audio/*");

    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

    Notification noti = new NotificationCompat.Builder(this)
            .setContentTitle("Download completed")
            .setContentText("Song name")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent).build();

    noti.flags |= Notification.FLAG_AUTO_CANCEL;

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, noti);

Problem

I've currently got a regular notification that tracks the progress of a download (of a song). Once the download is complete I'd like to make it so that if the user presses on the notification it opens up the song file in the default application that would handle that file type. I've tried searching but I'm unsure as to how to work with the PendingIntent and the MIME type when using .setDataAndType(). Could someone please explain or provide some example code for how I could set up the intent to open up the file from a specific file path in the default app? Thank you, Daniel

Original source