Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 367
Jimix Avatar asked Feb 24 '11 11:02

Jimix


People also ask

How do I send data from BroadcastReceiver to activity?

Intent intent = getIntent(); String message = intent. getStringExtra("message"); And then you will use message as you need. If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="@android:style/Theme.

What is the method name in BroadcastReceiver receive the message?

To receive SMS messages, use the onReceive() method of the BroadcastReceiver class. The Android framework sends out system broadcasts of events such as receiving an SMS message, containing intents that are meant to be received using a BroadcastReceiver.

When would you use a BroadcastReceiver?

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.

What does a BroadcastReceiver do?

A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.


1 Answers

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..

like image 59
Jignesh Dhua Avatar answered Sep 22 '22 13:09

Jignesh Dhua