Изображение кнопки воспроизведения/паузы в уведомлении, Android
Я реализовал музыкальный проигрыватель, который запускает пользовательское уведомление при воспроизведении аудио потока.
Все работает, и я могу воспроизводить/приостанавливать звук с помощью кнопки в уведомлении. Единственная проблема - кнопка изображения: она не может изменить изображение одним нажатием кнопки, чтобы указать воспроизведение/паузу.
Использование remoteViews.setImageViewResource() в RemoteReceiver не работает. Управление осуществляется с помощью BroadcastReceiver, и это код для активации уведомления из активности игрока:
public void setNotification(String songName){
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) getSystemService(ns);
@SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.ic_launcher, null, System.currentTimeMillis());
RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification_view);
notificationView.setImageViewResource(R.id.button1, R.drawable.pause);
notificationView.setTextViewText(R.id.textView1, songName);
//the intent that is started when the notification is clicked (works)
Intent notificationIntent = new Intent(this, PlayerActivity.class);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.contentView = notificationView;
notification.contentIntent = pendingNotificationIntent;
Intent switchIntent = new Intent("com.example.test.ACTION_PLAY");
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationView.setOnClickPendingIntent(R.id.play_pause, pendingSwitchIntent);
notificationManager.notify(1, notification);
}
Содержимое notification.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_alignParentLeft="true"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/ic_launcher"
android:id="@+id/imgAppIc" />
<TextView
android:layout_toRightOf="@id/imgAppIc"
android:singleLine="true"
android:id="@+id/textView1"
android:ellipsize="marquee"
android:layout_marginLeft="7dp"
android:layout_marginTop="10dp"
android:marqueeRepeatLimit ="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:layout_width="170dp"
android:layout_height="wrap_content"/>
<ImageButton
android:id="@+id/play_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/play"
/>
</RelativeLayout>
это класс RemoteRecivier
public class RemoteControlReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.notification_view);
if(action.equalsIgnoreCase("com.example.test.ACTION_PLAY")){
if(mediaplayer.isPlaying()){
mediaplayer.pause();
remoteViews.setImageViewResource(R.id.button1, R.drawable.play);
}
else {
mediaplayer.start();
remoteViews.setImageViewResource(R.id.button1, R.drawable.pause);
}
}
}
}
и, наконец, манифест
<receiver android:name=".RemoteControlReceiver">
<intent-filter>
<action android:name="com.Music.app.ACTION_PLAY" />
</intent-filter>
</receiver>
<activity android:name="PlayerActivity" />
Ответы
Ответ 1
Вам необходимо установить ваше уведомление .contentView в новый remoteView после его изменения, чтобы он мог обновлять само уведомление.
Значение, после того, как вы получите действие в своем BroadcastReceiver, заново создайте уведомление с нужным отображением кнопки (пауза или воспроизведение)
Надеюсь, что это поможет
Ответ 2
Это должно сработать. Просто сделайте notification
и notificationManager
статической глобальной переменной.
public class RemoteControlReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(action.equalsIgnoreCase("com.example.test.ACTION_PLAY")){
if(mediaplayer.isPlaying()){
mediaplayer.pause();
notificationView.setImageViewResource(R.id.button1, R.drawable.play);
notification.contentView = notificationView;
notificationManager.notify(1, notification);
}
else {
mediaplayer.start();
notificationView.setImageViewResource(R.id.button1, R.drawable.pause);
notification.contentView = notificationView;
notificationManager.notify(1, notification);
}
}
}
}
Ответ 3
Привет, ребята, вам нужно всего лишь обновить "messagesManager.notify(1, Notification);"
в вашем методе onReceiver после внесения изменений в то же уведомление.
Назначьте общедоступные статические функции для вашего уведомлений и уведомлений и используйте их в расширенном классе BroadcastReceiver.
Чтобы узнать точно, смотрите код ниже:
public void onReceive(Context context, Intent intent) {
String action1 = intent.getStringExtra("action1");
// String action2 = intent.getStringExtra("action2");
Log.i("Intent Received","Yes");
if(say)
{
if (action1.equals("PauseAction"))
{
performAction1();
say = false;
}
}
else if(!say)
{
if (action1.equals("PauseAction"))
{
performAction2();
say = true;
}
}
public void performAction1()
{
if (mediaPlayer!=null)
{
if(mediaPlayer.isPlaying())
{
playButtonImage.setImageResource(R.drawable.playbutton);
playButtonImage.setContentDescription("Play Button ");
notificationView.setImageViewResource(R.id.remoteViewImageView,R.drawable.playbutton);
mediaPlayer.pause();
play = true;
MainActivity.notificationManager.notify(1, notification);
}
Log.i("performAction1 called ","Yes");
}
}
public void performAction2()
{
if (mediaPlayer != null)
{
mediaPlayer.start();
playButtonImage.setImageResource(R.drawable.pause);
playButtonImage.setContentDescription("Pause Button");
notificationView.setImageViewResource(R.id.remoteViewImageView,R.drawable.pause);
MainActivity.notificationManager.notify(1, notification);
play = false;
Log.i("performAction2 called ", "Yes");
}
}
}
Ответ 4
Почему бы не использовать ImageView вместо ImageButton? С помощью ImageView вы можете просто изменить внешний вид с помощью removeViews.setImageViewResource(R.id.button1, R.drawable.pause);