在 android 上使用服务通过通知播放和暂停音乐

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

我正在尝试构建一个使用通知的应用程序,通过单击通知中存在的“play/pause”按钮,我可以播放和暂停音乐 没有错误但是当点击通知时音乐不会暂停。 谁能告诉我问题是什么

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));
                                            }
                                        });
    }
}

像这样构建您的 Notification,以便在两种情况下实现相同的行为:

  1. Notification 被点击时。

  2. 单击 Play/Pause 时。

    通知通知= 新 NotificationCompat.Builder(这个, channelId)
    .setContentTitle("Lecture en cours") .setContentText("Tahir ve Nafess") .setSmallIcon(R.drawable.ic_launcher_background) .addAction(R.drawable.ic_launcher_foreground, "Play/Pause", pPPendingIntent)
    // 我指的是这个 contentIntent
    .setContentIntent(pPPendingIntent)
    // .setPriority(Notification.PRIORITY_MAX)
    .build();

编辑:在 MusicServiceonCreate() 中注册 MyReceiver 时,您传递了错误的 IntentFilter 对象。应该是

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