Управление музыкальным проигрывателем в уведомлении
как установить уведомление с помощью воспроизведения/паузы, следующей и предыдущей кнопки в android.!
Я новичок в Android, а также при переполнении стека. Поэтому, пожалуйста, медведь со мной.
![enter image description here]()
Я устанавливаю уведомление, когда песня начинает играть, как показано ниже:
`
@SuppressLint("NewApi")
public void setNotification(String songName){
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) getSystemService(ns);
@SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.god_img, null, System.currentTimeMillis());
RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification_mediacontroller);
//the intent that is started when the notification is clicked (works)
Intent notificationIntent = new Intent(this, AudioBookListActivity.class);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentView = notificationView;
notification.contentIntent = pendingNotificationIntent;
notification.flags |= Notification.FLAG_NO_CLEAR;
//this is the intent that is supposed to be called when the button is clicked
Intent switchIntent = new Intent(this, AudioPlayerBroadcastReceiver.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0);
notificationView.setOnClickPendingIntent(R.id.btn_play_pause_in_notification, pendingSwitchIntent);
notificationManager.notify(1, notification);
}
`
Я создал BroadcastReceiver, как показано ниже:
`
private class AudioPlayerBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("intent action = " + action);
long id = intent.getLongExtra("id", -1);
if(Constant.PLAY_ALBUM.equals(action)) {
//playAlbum(id);
} else if(Constant.QUEUE_ALBUM.equals(action)) {
//queueAlbum(id);
} else if(Constant.PLAY_TRACK.equals(action)) {
//playTrack(id);
} else if(Constant.QUEUE_TRACK.equals(action)) {
//queueTrack(id);
} else if(Constant.PLAY_PAUSE_TRACK.equals(action)) {
// playPauseTrack();
System.out.println("press play");
} else if(Constant.HIDE_PLAYER.equals(action)) {
// hideNotification();
System.out.println("press next");
}
else {
}
}
}`
Теперь я устанавливаю специальное уведомление успешно, но как я могу обрабатывать кнопки уведомлений и его события, такие как воспроизведение/пауза, предыдущий и следующий... и т.д. Я также пытаюсь использовать широковещательный приемник, но не могу получить никакого ответа.
Ищу решение и рекомендации от экспертов, пожалуйста, помогите мне.
Спасибо заранее.
Ответы
Ответ 1
Вам нужно установить класс custom intent action
, а не AudioPlayerBroadcastReceiver
.
Создайте намерение с пользовательским именем действия, подобным этому
Intent switchIntent = new Intent("com.example.app.ACTION_PLAY");
Затем зарегистрируйте приемник PendingIntent
Broadcast
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 100, switchIntent, 0);
Затем установите a onClick
для управления воспроизведением, при необходимости выполните аналогичные пользовательские действия для других элементов управления.
notificationView.setOnClickPendingIntent(R.id.btn_play_pause_in_notification, pendingSwitchIntent);
Затем зарегистрируйте пользовательское действие в AudioPlayerBroadcastReceiver
, как это показано
<receiver android:name="com.example.app.AudioPlayerBroadcastReceiver" >
<intent-filter>
<action android:name="com.example.app.ACTION_PLAY" />
</intent-filter>
</receiver>
Наконец, при нажатии на макет Notification
RemoteViews
при воспроизведении игры вы получите play action
с помощью BroadcastReceiver
public class AudioPlayerBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equalsIgnoreCase("com.example.app.ACTION_PLAY")){
// do your stuff to play action;
}
}
}
EDIT: как установить фильтр намерений для широковещательного приемника, зарегистрированного в коде
Вы также можете установить Custom Action
через Intent filter
из кода для зарегистрированного Broadcast receiver
, подобного этому
// instance of custom broadcast receiver
CustomReceiver broadcastReceiver = new CustomReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
// set the custom action
intentFilter.addAction("com.example.app.ACTION_PLAY");
// register the receiver
registerReceiver(broadcastReceiver, intentFilter);