Воспроизведение предыдущей / следующей песни кнопками в уведомлении - PullRequest
0 голосов
/ 01 февраля 2019

У меня есть проигрыватель, в котором, когда пользователь выбирает песню, проигрыватель делает уведомление с 3 кнопками: предыдущий, воспроизведение, следующий.Эти кнопки нужны для выбора песен в фоновом режиме.Но когда я нажимаю на эту кнопку, ничего не происходит.Вот код уведомления:

Intent intentPrev = new Intent(this, NotificationReceiver.class);
        intentPrev.setAction(ACTION_PREV);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intentPrev);
        PendingIntent pendingIntentPrev = PendingIntent.getActivity(this, 0, intentPrev, PendingIntent.FLAG_UPDATE_CURRENT);

        Intent intentPlay = new Intent(this, NotificationReceiver.class);
        intentPlay.setAction(ACTION_PLAY);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intentPlay);
        PendingIntent pendingIntentPlay = PendingIntent.getActivity(this, 0, intentPlay, PendingIntent.FLAG_UPDATE_CURRENT);

        Intent intentNext = new Intent(this, NotificationReceiver.class);
        intentNext.setAction(ACTION_NEXT);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intentNext);
        PendingIntent pendingIntentNext = PendingIntent.getActivity(this, 0, intentNext, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.notification).
                setContentTitle(songs.get(songPos).getTitle()).setContentText(songs.get(songPos).getArtist()).
                addAction(R.drawable.previous, "Previous", pendingIntentPrev).addAction(R.drawable.pause, "Pause", pendingIntentPlay).
                addAction(R.drawable.next, "Next", pendingIntentNext);
        Notification notification = builder.build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, notification);

А вот код получателя:

package asus.example.com.player;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import java.util.Objects;

public class NotificationReceiver extends BroadcastReceiver {

    private final String    ACTION_PREV = "PREVIOUS";
    private final String    ACTION_PLAY = "PLAY";
    private final String    ACTION_NEXT = "NEXT";
    private final MyService service     = new MyService();

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Objects.equals(intent.getAction(), ACTION_PREV)){
            service.playPrev();
        }
        else if (Objects.equals(intent.getAction(), ACTION_NEXT)){
            service.playNext();
        }
    }
}

Также я добавил приемник в манифест:

<receiver
            android:name=".NotificationReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="PREVIOUS"/>
                <action android:name="PLAY"/>
                <action android:name="NEXT"/>
            </intent-filter>
        </receiver>

Когда я смотрелв отладчике я увидел, что класс Receiver не используется, но я не понимаю, почему

1 Ответ

0 голосов
/ 01 февраля 2019

Прямо сейчас вы отправляете трансляцию немедленно с такими заявлениями:

LocalBroadcastManager.getInstance(this).sendBroadcast(intentNext);

И вы говорите, что хотите начать Activity позже:

PendingIntent pendingIntentNext = PendingIntent.getActivity(this, 0, intentNext, PendingIntent.FLAG_UPDATE_CURRENT);

(Примечание: это все равно не будет работать, потому что в intentNext вы указываете класс, начинающийся с BroadcastReceiver, а не с Activity)

Это должно быть getBroadcast(), а не getActivity():

Intent intentNext = new Intent(this, NotificationReceiver.class);
intentNext.setAction(ACTION_NEXT);
PendingIntent pendingIntentNext = PendingIntent.getBroadcast(this, 0, intentNext, PendingIntent.FLAG_UPDATE_CURRENT);

Другое дело: вы используете '0' в качестве кода запроса (второй параметр) во всех ваших PendingIntent с.Вы должны использовать разные значения для кодов запроса , потому что два Intent с одним и тем же кодом запроса считаются одинаковыми Intent, поэтому вы получите все три уведомления Buttons вызывает то же действие.

...