Изменение значка кнопки уведомления при нажатии - PullRequest
0 голосов
/ 26 октября 2019

Я сделал пользовательский макет для своего уведомления, он имеет две кнопки, одну для воспроизведения и одну для приостановки музыки. Когда я нажимаю на каждую кнопку, трансляция отправляется в соответствующий класс.

notification

Теперь я хочу оставить только одну кнопку и (переключить) изменить значок кнопки, когда пользователь нажимает кнопку от воспроизведения до паузы инаоборот, я попробовал несколько вещей, чтобы поменял иконку (моя настоящая проблема), но пока не получилось.

В PlayerActivity.java я отображаю уведомление, вызывая эту строку.

NotificationGenerator.customBigNotification(getApplicationContext());

Вот код NotifcationGenerator:

package com.example.user.musicplayer;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

public class NotificationGenerator {
    private static final int NOTIFICATION_ID_OPEN_ACTIVITY = 1;
    private static final int NOTIFICATION_ID_CUSTOM_BIG = 1;

    public static void customBigNotification(Context context){
        RemoteViews expandedView = new RemoteViews(context.getPackageName(), R.layout.big_notification);
        NotificationCompat.Builder nc = new NotificationCompat.Builder(context);
        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent notifyIntent = new Intent(context, PlayerActivity.class);
        notifyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        notifyIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        String id = "mymusicplayer";
        CharSequence name = "player";
        String description = "player";
        int importance = NotificationManager.IMPORTANCE_LOW;

        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(id, name, importance);
            mChannel.setDescription(description);

            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);

            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

            nm.createNotificationChannel(mChannel);
        }



        nc.setContentIntent(pendingIntent);
        nc.setSmallIcon(R.drawable.ic_action_play);
        nc.setAutoCancel(true);
        nc.setCustomBigContentView(expandedView);
        nc.setContentTitle("Music Player");
        nc.setContentText("Control Audio");
        nc.getBigContentView().setTextViewText(R.id.textSongName, "Lorem Ipsum Dolor");

        setRemoteViews(expandedView, context);
        nm.notify(NOTIFICATION_ID_CUSTOM_BIG, nc.setChannelId(id).build());
    }

    private static void setRemoteViews(RemoteViews remoteViews, Context c) {

        // call broadcast when any control of notification is clicked.
        Intent playIntent = new Intent(c, PlayBroadcast.class);

        PendingIntent playPendingIntent = PendingIntent.getBroadcast(c, 0, playIntent, 0);

        // Using RemoteViews to bind custom layouts into Notification
        remoteViews.setOnClickPendingIntent(R.id.btnPlay, playPendingIntent);

        // call broadcast when any control of notification is clicked.
        Intent pauseIntent = new Intent(c, PauseBroadcast.class);

        PendingIntent pausePendingIntent = PendingIntent.getBroadcast(c, 0, pauseIntent, 0);

        // Using RemoteViews to bind custom layouts into Notification
        remoteViews.setOnClickPendingIntent(R.id.btnPause, pausePendingIntent);
    }

}

Вот код PlayBroadCast.java: (где получена трансляция с кнопки воспроизведения):

package com.example.user.musicplayer;

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

public class PlayBroadcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        MediaPlayer mP = PlayerActivity.mediaPlayer;
        if(!mP.isPlaying()){
            mP.start();

        }
    }
}

Извините, если объяснение неясно, потому что, если у меня могут быть правильные слова, чтобы объяснить это. Я бы гуглил это. Заранее спасибо.

...