将数据发送到可启动另一个活动 [英] Sending data to another activity that may be started

查看:154
本文介绍了将数据发送到可启动另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我使用将数据发送到可能会或可能不会运行另一个活动一个BroadcastReceiver。我使用的是意图在我的onReceive()方法,并把数据与putExtra()。该数据被发送到了活动,但活动的onCreate()方法被调用,即使该活动已在运行,并在前台,所以我想这是创建一个新的实例。我想只有onResume()调用,或者有一些其他的方式,我可以创建/启动的意图,如果它不存在,如果确实如此,只是它恢复。目前,该活动正在重建,而我不想这样。

I have a BroadcastReceiver that I'm using to send data to another activity which may or may not be running. I'm using the intent in my onReceive() method, and putting the data in with putExtra(). THe data gets sent to the activity, however, the activity's onCreate() method gets called even though the activity is already running and in the foreground, so I guess it's creating a new instance. I want to only have onResume() called, or perhaps there's some other way I can create/start the intent if it doesn't exist, and if it does, just have it 'resumed'. Right now, the activity is being recreated, and I do not want this.

public void onReceive(Context context, Intent intent) {
            intent.setClass(context, MyActivity.class);
            intent.putExtra("message", "the data here");
            //intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Log.d("sending msg", "msg");    
            context.startActivity(intent);    
       }

如果我不使用FLAG_ACTIVITY_NEW_TASK,一个RuntimeException是罚球,特别告诉我,如果我要开始的东西是不是一个活动,我必须用一个活动 FLAG_ACTIVITY_NEW_TASK

If I do not use FLAG_ACTIVITY_NEW_TASK, a RuntimeException is throw, specifically telling me that if I want to start an activity from something that is not an activity, I must use FLAG_ACTIVITY_NEW_TASK.

推荐答案

我结束了转播(内部)的分析的信息,我的BroadcastReceiver的是越来越在的actvity,在code,注册事件,有一个小处理方法在一个私人创建的接收机。这是一个很好的解决方案,因为我知道,这个活动会一直运行在我的情况。

I ended up rebroadcasting (internally) the parsed information that my BroadcastReceiver was getting in. The actvity, in code, registered for the event and had a small handler method in a private-created receiver. This was a good solution as I know that this activity would always be running in my case.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        receiver = new BroadcastReceiver(){

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("activity", "in local defined receiver");
                if(intent.getAction().equals(CustomInternalSendSmsAction) )
                {
                    handlePassedData(intent);               
                }
            }
        };
        this.registerReceiver(receiver, new IntentFilter(CustomInternalSendSmsAction));
}

这篇关于将数据发送到可启动另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆