我正在使用 Intents 来保存数据并在我的应用程序的其他地方恢复它们。我在其他地方使用过它们,但现在,它并没有像我希望的那样工作。
public class GCMIntentService extends GCMBaseIntentService {
public GCMIntentService() {
super(ConstantsGCM.GCM_SENDER_ID);
}
@Override
protected void onMessage(Context context, Intent intent) {
...
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notManager = (NotificationManager) context.getSystemService(ns);
String room = intent.getExtras().getString(ConstantsGCM.GCM_ROOM);
Intent notIntent;
PendingIntent contIntent;
Notification notif;
notif = new Notification(icon, textStatus, time);
notIntent = new Intent(contexto,RoomsActivity2.class);
Bundle b2 = new Bundle();
b2.putString(ConstantsRooms.ROOM, room);
notIntent.putExtras(b2);
contIntent = PendingIntent.getActivity(contexto, 0, notIntent, 0);
notif.setLatestEventInfo(contexto, tittle, description, contIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notManager.notify((int)(Math.random()*1000), notif);
此代码在收到通知时执行。当我单击此通知时,它会执行 Activity RoomsActivities2.class。在这里,我只是调用这段代码:
public String getMessageString(String cod){
String result = "";
bundle = getIntent().getExtras();
if (bundle != null){
result = bundle.getString(cod);
}
return result;
}
但是,我没有得到保存在 Intent 中的最后数据。怎么了?我想我没有正确使用它。为什么我无法从 Activity 中获取数据?
我认为正在发生的事情是: 该应用程序收到很多通知,第一个工作正常。但是,如果我不断收到更多通知,数据不会被覆盖,我总是会收到第一个通知,尽管当我调试代码时,我正在设置另一个数据。
最佳答案
好吧,我已经有一段时间没有处理未决 Intent 了,但我记得两件事:
替换:
contIntent = PendingIntent.getActivity(contexto, 0, notIntent, 0);
与:
contIntent = PendingIntent.getActivity(contexto, 0, notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
这将使 bundle 一直存在。
但是该标志将用最新的一个覆盖任何现有的未决 Intent ,您可能不希望这样。
如果您有多个来自同一上下文且具有相同 Intent (但不同的包!)的多个未决 Intent ,您可以使用第二个参数。
contIntent = PendingIntent.getActivity(contexto, requestCode, notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
只要每个未决 Intent 都有一个唯一的requestCode
,即使谷歌开发人员的文档说没有使用该参数,它实际上确实用于识别未决 Intent 并允许重复不同的包。
关于android - 如何正确使用Intent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17224307/