想着通过Notification 发送一条通知
点击通知跳转到一个新的activity
在activity中得到Notification的id,从而能够cancel掉Notification。
但是在Notification发送时候,封装好了intent的数据。
当跳转到了 新的activity的时候,getIntent 什么都得不到。百度查询了好久都没有一个正解。
无奈翻墙google继续寻找原因。最后在 http://stackoverflow.com
//关键两点1.
//传递数据想要成功,需要设置这里的flag参数
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//2,新Activity中重写onNewIntent方法
新Activvity的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
int tagId = bundle.getInt("tag");
NotificationManager nm = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Log.e("OtherActivity", "tag = tagId = "+tagId);
nm.cancel(tagId);
}
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
setIntent(intent);
}
//发送广播的代码
private void initNotification() {
// 1:获取NotificationManager
NotificationManager nm = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
// 2、封装发送的信息
Notification mNotification = new Notification();
mNotification.icon = R.drawable.qq;
mNotification.tickerText = "收到消息时提示内容";
mNotification.defaults = Notification.DEFAULT_SOUND;
Intent intent = new Intent(this, OtherActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("tag", 100);
intent.putExtras(bundle);
//传递数据想要成功,需要设置这里的flag参数
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotification.setLatestEventInfo(this, "contentTitle", "contentText",
mPendingIntent);
// 3、发送通知
nm.notify(100, mNotification);
}
原文详解;