Skip to content Skip to sidebar Skip to footer

Start Broadcast Receiver From An Activity In Android

I would like to start a broadcast receiver from an activity. I have a Second.java file which extends a broadcast receiver and a Main.java file from which I have to initiate the bro

Solution 1:

use this why to send a custom broadcast:

Define an action name:

publicstaticfinalStringBROADCAST="PACKAGE_NAME.android.action.broadcast";

AndroidManifest.xml register receiver :

<receiverandroid:name=".myReceiver" ><intent-filter ><actionandroid:name="PACKAGE_NAME.android.action.broadcast"/></intent-filter></receiver>

Register Reciver :

IntentFilterintentFilter=newIntentFilter(BROADCAST);
registerReceiver( myReceiver , intentFilter);

send broadcast from your Activity :

Intentintent=newIntent(BROADCAST);  
        Bundleextras=newBundle();  
        extras.putString("send_data", "test");  
        intent.putExtras(extras);  
        sendBroadcast(intent);

YOUR BroadcastReceiver :

privateBroadcastReceivermyReceiver=newBroadcastReceiver() {

        publicvoidonReceive(Context context, Intent intent) {
            // TODO Auto-generated method stubBundleextras= intent.getExtras();
           if (extras != null){  
           {
                    rec_data = extras.getString("send_data");
            Log.d("Received Msg : ",rec_data);
            }
        }
    };

for more information for Custom Broadcast see Custom Intents and Broadcasting with Receivers

Solution 2:

Solution 3:

For that you have to broadcast a intent for the receiver, see the code below :-

Intent intent=newIntent();
getApplicationContext().sendBroadcast(intent);

You can set the action and other properties of Intent and can broadcast using the Application context, Whatever action of Intent you set here that you have to define in the AndroidManifest.xml with the receiver tag.

Solution 4:

Check this answer:

https://stackoverflow.com/a/5473750/928361

I think if you don't specify anything in the IntentFilter, you need to tell the intent the receiver class.

Post a Comment for "Start Broadcast Receiver From An Activity In Android"