在notification中设置PendingIntent

本文探讨了如何在Android通知栏创建notification,并结合PendingIntent实现点击控制媒体播放的intent。通过示例代码,解释了为何不能使用LocalBroadcastManager注册receiver的原因,因为notification所在进程不同于应用进程。
摘要由CSDN通过智能技术生成


在android屏幕的通知栏中增加notification,以显示mediaplayer控制面板
点击控制面板的按钮将发送intent来控制mediaplayer
这些intent将以PendingIntent的形式绑定到控制面板上的按钮上


不能工作的代码:

public void sendNotification(int status) {

 if (playingFile != null) {
  
  /**
   * 给notification构建intent
   */
   
  //如下是在notification中给remoteview设置PendingIntent
  //receiver按NOTIFICATION_ACTION进行过滤
  //过滤之后按putExtra中设置的参数分辨命令
  //
  //陷阱是setAction()和PendingIntent.getBroadcast()以及FLAG_UPDATE_CURRENT
  //如下代码,最终所有PendingIntent都会变成最后一个!
  //猜测,无论从上到下生成多少个PendingIntent
  //但同一条ACTION的PendingIntent.getBroadcast()背后只对应一个静态变量!
  //也即这四个实际上是一个PendingIntent
  //FLAG_UPDATE_CURRENT及另外几个参数的说明也非常不易懂,看得很晕
  //
  //解决方案是,设置receiver可以过滤出多条ACTION而不是一条
  //不按putExtra里面设置的数据进行分辨
  //而是直接根据不同的ACTION来分辨命令
  //可以工作的代码在后面
  Intent resultIntentLast = new Intent(this, PlayService.class);
  resultIntentLast.setAction(LocalConst.NOTIFICATION_ACTION);
  resultIntentLast.putExtra(LocalConst.NOTIFICATION_OP, LocalConst.op_last);
  PendingIntent pendingIntentLast = PendingIntent.getBroadcast(this, 0,
    resultIntentLast, PendingIntent.FLAG_UPDATE_CURRENT);

  Intent resultIntentNext = new Intent(this, PlayService.class);
  resultIntentNext.setAction(LocalConst.NOTIFICATION_ACTION);
  resultIntentLast.putExtra(LocalConst.NOTIFICATION_OP, LocalConst.op_next);
  PendingIntent pendingIntentNext = PendingIntent.getBroadcast(this, 0,
    resultIntentNext, PendingIntent.FLAG_UPDATE_CURRENT
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值