1. 程式人生 > >安卓 notification 使用pendingintent傳值時傳值重複或無效的問題

安卓 notification 使用pendingintent傳值時傳值重複或無效的問題

 PendingIntent pendingIntent2 = PendingIntent.getActivity(mContent, 0,  

    intent, PendingIntent.FLAG_UPDATE_CURRENT);  

pendingintent.getactivity方法中第二個引數和第4個引數會影響intent中extras的內容 第二個值是id  相當於這個pendingintent的標籤 同一個標籤的pendingintent只會顯示最新的 intent也是最新的intent  第4個引數會影響intent的extras的內容 這裡常用的flag標籤如下

FLAG_ONE_SHOT:

this PendingIntent can only be used once. If set, after send() is called on it, it will be automatically canceled for you and any future attempt to send through it will fail.

FLAG_NO_CREATE:if the described PendingIntent does not already exist, then simply return null instead of creating it.

FLAG_CANCEL_CURRENT:
if the described PendingIntent already exists, the current one is canceled before generating a new one. You can use this to retrieve a new PendingIntent when you are only changing the extra data in the Intent; by canceling the previous pending intent, this ensures that only entities given the new data will be able to launch it. If this assurance is not an issue, consider FLAG_UPDATE_CURRENT.


FLAG_UPDATE_CURRENT: if the described PendingIntent already exists, then keep it but its replace its extra data with what is in this new Intent. This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.

其中FLAG_UPDATE_CURRENT是最常用的 描述的Intent有更新的時候需要用到這個flag去更新你的描述,否則元件在下次事件發生或時間到達的時候extras永遠是第一次Intent的extras。使用FLAG_CANCEL_CURRENT也能做到更新extras,只不過是先把前面的extras清除,FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT的區別在於能否新new一個Intent,FLAG_UPDATE_CURRENT能夠新new一個Intent,而FLAG_CANCEL_CURRENT則不能,只能使用第一次的Intent。