注意通知中PendingIntent.getActivity(Contextcontext, int requestCode,Intentintent, int flags)这几个参数:

context The Context in which this PendingIntent should start the activity.
requestCode Private request code for the sender (currently not used).
intents Array of Intents of the activities to be launched.
flags May beFLAG_ONE_SHOT,FLAG_NO_CREATE,FLAG_CANCEL_CURRENT,FLAG_UPDATE_CURRENT, or any of the flags as supported byIntent.fillIn()to control which unspecified parts of the intent that can be supplied when the actual send happens.
google API中介绍requestCode中说明是当前未使用,一般都会赋值为0,但是当你发送多个通知,且每个通知都包含Extras时,这个就有用了。这个值可以用来标识不同通知中的Intent,主要是结合后面的flags来使用,比如,发送两个通知,id分别是1和2,当第二次发送1、2的通知时,需要更新前一次通知中的intent内容,如果不用requestCode来标识一下,则默认用最后一次发的通知覆盖前几次的通知intent。

正确是使用方法是:PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); requestCode来标识不同通知,flags中的PendingIntent.FLAG_UPDATE_CURRENT用来使用后面通知更新前面通知,使用这个flag要注意,intent一定不能为null,否则会报空指针错误。

另外,当我们把Activity 启动模式设置为 singleTask 之后 当我们下次 再去 用Intent 启动 这个 Activity 的时候 就不会去调用 onCreate方法 也不能在onRestart()方法中取,而是去调用onNewIntent()方法 然后把Intent中的数据传给它;

  • <activityandroid:name="TestActivity"
  • android:launchMode="singleTask"/> 示例:

    @Override
    protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    int hasMsgNotifyFlag = 0;
    if(intent!=null){
    Bundle bundle = intent.getExtras();
    if(bundle!=null){
    hasMsgNotifyFlag = bundle.getInt("id");
    }
    Log.i( "main tab msg=>", hasMsgNotifyFlag + "");
    }
    }

    /**
    * 添加一个notification
    */
    public void addNotification(Context context, int id, boolean flag){
    NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.icon, "hello,here", System.currentTimeMillis());
    notification.flags = Notification.FLAG_AUTO_CANCEL;
    Intent intent = new Intent(context, TestActivity.class);
    Bundle bundle = new Bundle();
    bundle.putInt("id", id);
    intent.putExtras(bundle);
    PendingIntent contentIntent = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, "有新消息", id + "", contentIntent);
    nm.notify(id, notification);
    }






  • 更多相关文章

    1. android 定时发送短信实现
    2. Androidの发送Email
    3. android 发送邮件
    4. android 广播传参数
    5. Android与Java AIO实现简单Echo服务器与客户端
    6. android 向serverGet和Post请求的两种方式,android向server发送
    7. Android(安卓)BroadcastReceiver介绍
    8. A20红外遥控器与Android功能的适配
    9. Android各版本适配之8.0

    随机推荐

    1. 框架模式MVC 在Android中的使用
    2. Android(安卓)翻页效果 电子书
    3. Android+OTA+升级之一:编译升级包---make+
    4. MVP+Retrofit2+RxJava2练手项目,玩Android
    5. Android开发心得——网页通过webview调用
    6. Android实现任意分辨率视频编码的思考与
    7. Android(安卓)Kotlin 开发踩坑之旅
    8. Android中使用GreenDao的坑整理
    9. 国内主流Android安卓应用市场简介
    10. Android———Layout:TableLayout