Start Broadcast Receiver from an activity in android

后端 未结 4 690
我在风中等你
我在风中等你 2020-12-09 04:04

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

相关标签:
4条回答
  • 2020-12-09 04:26

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

    Intent intent=new Intent();
    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.

    0 讨论(0)
  • 2020-12-09 04:30

    use this why to send a custom broadcast:

    Define an action name:

    public static final String BROADCAST = "PACKAGE_NAME.android.action.broadcast";
    

    AndroidManifest.xml register receiver :

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

    Register Reciver :

    IntentFilter intentFilter = new IntentFilter(BROADCAST);
    registerReceiver( myReceiver , intentFilter);
    

    send broadcast from your Activity :

    Intent intent = new Intent(BROADCAST);  
            Bundle extras = new Bundle();  
            extras.putString("send_data", "test");  
            intent.putExtras(extras);  
            sendBroadcast(intent);
    

    YOUR BroadcastReceiver :

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                 Bundle extras = 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

    0 讨论(0)
  • 2020-12-09 04:31

    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.

    0 讨论(0)
  • 2020-12-09 04:36

    check this tutorial here you will get all help about broadcast including how to start service from activity or vice versa

    http://www.vogella.de/articles/AndroidServices/article.html

    0 讨论(0)
提交回复
热议问题