如何正确使用Intent

时间:2013-06-20 21:40:57

标签: android android-intent

我正在使用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中保存最后的数据。怎么了?我想我没有正确使用它。为什么我无法从活动中获取数据?

我认为它正在发生的事情是: 该应用程序获得了很多通知,第一个正常工作。但是,如果我不断获得更多通知,数据不会覆盖,我总是得到第一个,但是当我调试代码时,我正在设置另一个数据。

1 个答案:

答案 0 :(得分:2)

好的,自从我使用待处理的意图以来已经有一段时间了,但我记得有两件事:

取代:

contIntent = PendingIntent.getActivity(contexto, 0, notIntent, 0);

with:

contIntent = PendingIntent.getActivity(contexto, 0, notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

这将保持捆绑。

但该标志将覆盖任何现有的最新暂定意图,您可能不希望这样。

如果您有相同意图的相同上下文中的多个待处理意图(但不同的包!),则可以使用第二个参数。

contIntent = PendingIntent.getActivity(contexto, requestCode, notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

只要每个待处理的意图都有唯一的requestCode,即使Google开发者的文档说未使用该参数,它实际上也可用于识别待处理的意图并允许使用不同的包进行重复。

相关问题