Call an activity method from a BroadcastReceiver. Is it possible?

笑着哭i 提交于 2019-12-10 13:27:50

问题


I'm stuck developing an app because I need to call a method of my activity when a BroadcastReceiver is triggered. I want the BroadcastReceiver to detect when a network connection goes down and call a method of my activity which I've already written.

I've been searching and I found that more people had asked this before but nobody got an answer about how to do it.

I think that maybe android's API doesn't allow it. If it's impossible to call a method of my activity from the BroadcastReceiver are there other ways to do this?

Thanks.


回答1:


Try something like this..

In you activity code write

BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            myActivityMethod();// Here you call method
        }
    };

    registerReceiver(connectionReceiver, new IntentFilter("com.test.NET_CONNECTION"));

And in your service write

Intent intent = new Intent("com.test.NET_CONNECTION");
        sendBroadcast(intent);

If any confusion let me know i'll try to solve..



来源:https://stackoverflow.com/questions/5104235/call-an-activity-method-from-a-broadcastreceiver-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!