javaandroidandroid-studioserviceandroid-notifications

play and pause the music trough a notification using Service on android


I m trying to build an app where I use a notification and by clicking on "play/pause" button that exists in the notification I can play and pause the music there is no error but when click on the notification the music does not pause. can someone tell me what is the problem

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/start"
        android:text="start"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/stop"
        android:text="stop"/>



</LinearLayout>

MusicService.java

    package com.example.test3;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

public class MusicService extends Service {
    MyReceiver recev;
    private MediaPlayer player;


    public MusicService(){}
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void onCreate() {

        recev=new MyReceiver();
        registerReceiver(recev,new IntentFilter("playpause"));
        player=MediaPlayer.create(this,R.raw.tn);
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent startIntent, int flags, int startId) {

//intent du clique notif
                Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
// intent du clique bouton play/pause
        PendingIntent pPPendingIntent = PendingIntent.getBroadcast(this, 0, new
                Intent("PlayPause"), PendingIntent.FLAG_UPDATE_CURRENT);

// Notification Channel
                NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


        String channelId = "my_channel_id";
        CharSequence channelName = "My Channel";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new
                    NotificationChannel(channelId, channelName, importance);
            notificationManager.createNotificationChannel(notificationChannel);}
                Notification notification =
                new NotificationCompat.Builder(this, channelId)
                        .setContentTitle("Lecture en cours")
                        .setContentText("Tahir ve Nafess")
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .addAction(R.drawable.ic_launcher_foreground, "Play/Pause", pPPendingIntent)
                        .setContentIntent(pendingIntent)
// .setPriority(Notification.PRIORITY_MAX)
                        .build();
        startForeground(110, notification);player.start();return START_STICKY;}

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player.isPlaying()) player.stop();
        unregisterReceiver(recev);
    }



    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals("PlayPause")) {
                if(player.isPlaying()) {player.pause();}
                else {player.start();}
            }
        }
    }
}

MainActivity.java

package com.example.test3;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
     Button play,stop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play=(Button)findViewById(R.id.start);
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startService(new Intent(getApplicationContext(),
                        MusicService.class));
            }
        });


        stop=(Button)findViewById(R.id.stop);
        stop.setOnClickListener(new
                                        View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                stopService(new
                                                        Intent(getApplicationContext(),
                                                        MusicService.class));
                                            }
                                        });
    }
}

Solution

  • Build your Notification like this so that same behaviour is achieved on both cases :

    1. when Notification is clicked.
    2. when Play/Pause is clicked.
    Notification notification =
                        new NotificationCompat.Builder(this, channelId)                       
        .setContentTitle("Lecture en cours")
        .setContentText("Tahir ve Nafess")
        .setSmallIcon(R.drawable.ic_launcher_background)
        .addAction(R.drawable.ic_launcher_foreground, "Play/Pause", pPPendingIntent)  
         // I was referring to this contentIntent  
         .setContentIntent(pPPendingIntent)  
        // .setPriority(Notification.PRIORITY_MAX)  
         .build();
    

    Edit: While registering your MyReceiver in onCreate() of your MusicService, you passed the wrong IntentFilter object. It should be

    //this is wrong as you are only going to handle PlayPause and not playpause  
    //registerReceiver(recev,new IntentFilter("playpause"));
    registerReceiver(recev, new IntentFilter("PlayPause"));