Управление запуском / остановкой в ​​области уведомлений для пользовательского аудиоплеера - PullRequest
0 голосов
/ 04 июня 2019

Я публикую свое решение для пользовательских элементов управления медиаплеера, используя класс уведомлений. Я надеюсь, что это помогает другим людям и экономит их время.

Новый androidx имеет особый стиль для объектов медиаплеера, который я не видел в их документах, но прекрасно работает:

.setStyle(new androidx.media.app.NotificationCompat.MediaStyle())

Убедитесь, что имеется большой и маленький значок.

Кнопки добавляются с помощью «addAction». Этот метод требует ожидания намерения. Это создается как трансляция, но остается в контексте приложения. В этом контексте я зарегистрировал два BroadcastRecivers: один для кнопки воспроизведения, а другой для кнопки паузы. Может быть сделано с одним и затем переключателем / кейсом конечно.

Наконец, важно создать канал уведомлений. Без этого кода уведомление не отображается вообще.

public class PlayBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Play!! Starting the media player here.", Toast.LENGTH_LONG).show();
    }
}

public class StopBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Pause!! Pausing the media player here.", Toast.LENGTH_LONG).show();
    }
}

   void initPlayerControls() {
        Intent notifyIntent = new Intent(this, MainActivity.class);
        PendingIntent notifyPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        notifyIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        final String PLAY = "tech.mycompany.app.PLAY";
        Intent playIntent = new Intent(PLAY);
        PendingIntent playPendingIntent =
                PendingIntent.getBroadcast(getBaseContext(), 0, playIntent, 0);
        IntentFilter playIntentFilter = new IntentFilter();
        playIntentFilter.addAction(PLAY);
        getBaseContext().registerReceiver(new PlayBroadcastReceiver(),playIntentFilter);

        final String STOP = "tech.mycompany.app.STOP";
        Intent stopIntent = new Intent(STOP);
        PendingIntent stopPendingIntent =
                PendingIntent.getBroadcast(getBaseContext(), 0, stopIntent, 0);
        IntentFilter stopIntentFilter = new IntentFilter();
        stopIntentFilter.addAction(STOP);
        getBaseContext().registerReceiver(new StopBroadcastReceiver(),stopIntentFilter);

        final Notification notification = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CH)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setSmallIcon(R.drawable.top_logo)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.top_logo))
                .addAction(R.drawable.icon_play, "Play", playPendingIntent)  // #1
                .addAction(R.drawable.icon_pause, "Pause", stopPendingIntent)  // #2
                .setContentTitle("Wonderful music")
                .setStyle(new androidx.media.app.NotificationCompat.MediaStyle())
                .setContentIntent(notifyPendingIntent)
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setColor(ContextCompat.getColor(getApplicationContext(), R.color.app_medium_color_transparent))
                .build();

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CH, "player", importance);
            channel.setDescription("Player channel");
            NotificationManager nm = getSystemService(NotificationManager.class);
            if (null != nm) {
                nm.createNotificationChannel(channel);
            }
        }

        // notificationId is a unique int for each notification that you must define
        notificationManager.notify(888, notification);
    }

Screenshot of the player controls

...