I will try to provide the solution I used, and most music players also use the same method to display player controls in the notification bar.
I am launching a service that is used to control Media Player and all its controls. Activity The user control interacts with the Service by sending Intents to the service, for example
Intent i = new Intent(MainActivity.this, MyRadioService.class); i.setAction(Constants.Player.ACTION_PAUSE); startService(i);
To get intentions and perform an action in the Service class, I use the following code in the onStartCommand service method
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent.getAction().equals(Constants.Player.ACTION_PAUSE)) { if(mediaPlayer.isPlaying()) { pauseAudio(); } }
Now, to accurately answer your question, to show a notification with playback controls. You can call the following methods to display a notification using controls.
// showNotification private void startAppInForeground() { // Start Service in Foreground // Using RemoteViews to bind custom layouts into Notification RemoteViews views = new RemoteViews(getPackageName(), R.layout.notification_status_bar); // Define play control intent Intent playIntent = new Intent(this, MyRadioService.class); playIntent.setAction(Constants.Player.ACTION_PLAY); // Use the above play intent to set into PendingIntent PendingIntent pplayIntent = PendingIntent.getService(this, 0, playIntent, 0); // binding play button from layout to pending play intent defined above views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent); views.setImageViewResource(R.id.status_bar_play, R.drawable.status_bg); Notification status = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { status = new Notification.Builder(this).build(); } status.flags = Notification.FLAG_ONGOING_EVENT; status.icon = R.mipmap.ic_launcher; status.contentIntent = pendingIntent; startForeground(Constants.FOREGROUND_SERVICE, status);
} Hope this really helps you. And you can achieve what you want. Happy coding :)
Ankit Gupta Mar 29 '18 at 8:29 2018-03-29 08:29
source share