Aftab Safdar
Aftab Safdar

Reputation: 668

How to add a notification to a MediaPlayer Service?

I have a working MediaPlayer app. The MainActivity (MyListActivity.java) binds itself to a Service (MediaService.java). The Service plays the music in the background.

I would like to know a way to add a notification so the user can control the tracks through it. I am using an Interface to pass the data from the Service to the Activity.

I have no clue where to start. I tried the Notifications tutorial on the Android Documentation, but I don't know how to add buttons and I cannot find a decent tutorial for RemoteViews.

This is what I have for my notification.

MediaService.java

    play(Track track) {
        ...
        showNotification(track);
    }

    showNoticiation(Track track){
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.dj_plink_avatar)
                .setContentTitle(track.getTitle())
                .setContentText(track.getGenre());

        Intent resultIntent = new Intent(this, MyListActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MyListActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent pIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pIntent);

        notificationManager = (NotificationManager) getSystemService(Context
                .NOTIFICATION_SERVICE);
        notificationManager.notify(notificationID, builder.build());
    }

PS: Api 15 minimum please :)

Upvotes: 0

Views: 2027

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 199880

NotificationCompat.MediaStyle, part of AppCompat, does all of the styling required and works back to API 7.

You'll still need to build your own PendingIntents for each action, but those can be done any way that makes sense. Generally, that involves using PendingIntent.getService() with an Intent pointing to your Service and an action you can using in onStartCommand() to distinguish which button was pressed.

Note: make sure you are using v7.app.NotificationCompat, not the v4 version.

Upvotes: 1

Related Questions