描述:使用Notifaction時,使用到PendingIntent中使用intent傳值的問題,接收Activity接收時獲取到的內容為null。
解決:
flags有四個取值:
int FLAG_CANCEL_CURRENT:如果該PendingIntent已經存在,則在生成新的之前取消當前的。
int FLAG_NO_CREATE:如果該PendingIntent不存在,直接返回null而不是創建一個PendingIntent。
int FLAG_ONE_SHOT:該PendingIntent只能用一次,在send()方法執行后,自動取消。
int FLAG_UPDATE_CURRENT:如果該PendingIntent已經存在,則用新傳入的Intent更新當前的數據。
我們需要把最后一個參數改為PendingIntent.FLAG_UPDATE_CURRENT,這樣在啟動的Activity里就可以用接收Intent傳送數據
的方法正常接收。
發送方code:
Intent intent = new Intent(context, XXActivity.class);
intent.putExtra("recFile", recName);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
builder.setTicker("新的通知");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("收到新的通知");
builder.setContentText("您有一條新的通知");
builder.setContentIntent(pendingIntent);
Notification notification = builder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
manager.notify(NOTIFACTION_FLAG_CODE, notification);
接收方code:
String recFileName = getIntent().getStringExtra("recFile");
if (recFileName != null) {
//處理邏輯...
}