[英]Change play button to pause button in notification
當我在我開發的播放器的通知上按下播放按鈕時,我需要將播放按鈕替換為暫停按鈕,反之亦然。 我在我的服務類中有內部廣播接收器類和方法 onPrepared,我在其中定義了通知。 在廣播接收器中,我試圖做這樣的事情(見代碼段),但我得到空指針異常。 如何通過正確暫停播放按鈕來更改播放按鈕?
enter code here case _Constants.ACTION_PLAY:
Toast.makeText(context, "Play", Toast.LENGTH_SHORT).show();
if(isPlaying())
{
status.contentView.setViewVisibility(R.drawable.icon_pause, View.INVISIBLE);
status.contentView.setViewVisibility(R.drawable.icon_play, View.VISIBLE);
pausePlayer();
}else {
status.contentView.setViewVisibility(R.drawable.icon_play, View.INVISIBLE);
status.contentView.setViewVisibility(R.drawable.icon_pause, View.VISIBLE);
go();
}
下面是 onPrepared 方法中動作按鈕的聲明:
enter code here
Intent closeIntent = new Intent(this, NotificationReceiver.class).setAction(_Constants.ACTION_EXIT);
PendingIntent pendingCloseIntent = PendingIntent.getBroadcast(this,0 ,closeIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Intent favoriteIntent = new Intent(this, NotificationReceiver.class).setAction(_Constants.ACTION_FAVORITE);
PendingIntent pendingFavoriteIntent = PendingIntent.getBroadcast(this, 1, favoriteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent prevIntent = new Intent(this,NotificationReceiver.class).setAction(_Constants.ACTION_PREVIUOS);
PendingIntent pendingPrevIntent = PendingIntent.getBroadcast(this,2,prevIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this,NotificationReceiver.class).setAction(_Constants.ACTION_NEXT);
PendingIntent pendingNextIntent = PendingIntent.getBroadcast(this,5,nextIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Intent playIntent = new Intent(this,NotificationReceiver.class).setAction(_Constants.ACTION_PLAY);
PendingIntent pendingPlayIntent = PendingIntent.getBroadcast(this,4,playIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap artwok = BitmapFactory.decodeResource(getResources(), R.drawable.ic_player);
status =new NotificationCompat.Builder(this,_Constants.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(songTitle)
.setContentText(songArtist)
.setLargeIcon(artwok)
.setContentIntent(pendInt)
.setOngoing(true)
//change then null by the required intent to make it work
.addAction(R.drawable.ic_favorite_empty,"Mark Favorite",pendingFavoriteIntent)
.addAction(R.drawable.icon_previous, "Previous",pendingPrevIntent)
.addAction(R.drawable.icon_play,"Play", pendingPlayIntent)
//.addAction(R.drawable.icon_pause,"Pause",pendingPauseIntent)
.addAction(R.drawable.icon_next,"Next",pendingNextIntent)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(1,2,3)
.setMediaSession(mediaSessionCompat.getSessionToken()))
.addAction(R.drawable.ic_close, "EXIT",pendingCloseIntent)
.setSubText("Now playing...")
.build();
status.flags=Notification.FLAG_ONGOING_EVENT;
startForeground(1,status);
您可以在 xml 文件的同一位置創建 2 個按鈕播放和暫停。 當您點擊播放時,將其可見性設置為 GONE 並將暫停按鈕 VISIBILITY 設置為 VISIBLE,反之亦然
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.