最近使用notification,对多个notification引发的问题总结如下(只是我碰到的):
1.多个通知间,点其中一个可能取到另一个通知的内容(通知的添加的代码相似)
2.多个通知间,点击完其中一个通知,导致另外一个通知无法点击
下面贴上自己的一段测试代码:
-
public class NotificationActivity extends Activity {
-
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
Button button = (Button) findViewById(R.id.button1);
-
EditText editText = (EditText) findViewById(R.id.editText1);
-
editText.setHeight(100);
-
button.setOnClickListener(new OnClickListener() {
-
-
@Override
-
public void onClick(View v) {
-
-
addNotification(2);
-
try {
-
Thread.sleep(2000);
-
} catch (InterruptedException e) {
-
-
e.printStackTrace();
-
}
-
addNotification(1);
-
}
-
});
-
-
}
-
-
-
-
-
private void addNotification(int id){
-
NotificationManager nm = (NotificationManager)this.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(this, Notification2Activity.class);
-
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-
intent.putExtra("id", id + "");
-
PendingIntent contentIntent = PendingIntent.getActivity(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
-
notification.setLatestEventInfo(this, "有新消息", id + "", contentIntent);
-
nm.notify(id, notification);
-
}
-
}
-
public class Notification2Activity extends Activity {
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main2);
-
Log.i("Notification2Activity 收到id:", getIntent().getStringExtra("id"));
-
}
-
-
}
这是我测试通过,没问题后的代码.
现在说说上述两个问题的症状在哪?
1.PendingIntent.FLAG_UPDATE_CURRENT,如果设置PendingIntent.FLAG_ONE_SHOT,PendingIntent 紧紧只能被点击一次.
PendingIntent.FLAG_UPDATE_CURRENT具体代表啥,去看源码吧.
2.
-
public static PendingIntent getActivity(Context context, int requestCode,
-
Intent intent, int flags) {
-
String packageName = context.getPackageName();
-
String resolvedType = intent != null ? intent.resolveTypeIfNeeded(
-
context.getContentResolver()) : null;
-
try {
-
IIntentSender target =
-
ActivityManagerNative.getDefault().getIntentSender(
-
IActivityManager.INTENT_SENDER_ACTIVITY, packageName,
-
null, null, requestCode, intent, resolvedType, flags);
-
return target != null ? new PendingIntent(target) : null;
-
} catch (RemoteException e) {
-
}
-
return null;
-
}
这是获取PendingIntent的源码,
第二个参数requestCode,代表着发送者的一个标识,用来区分不同通知的接收者.
所以这地方需要设置下,不能相同,否则产生前面提到的第一个的问题