Search code examples
androidbroadcastreceiver

Multiple custom broadcasting (how to handle)


I want to add a custom broadcast receiver to my app. and I have 3 methods that should do the broadcast. and in my onReceive method i want to identify which method did the broadcast. I have 3 methods like this

public void method01(View v){
    int flag = 1;
    Intent intent = new Intent();
    intent.addFlags(flag);
    broadcastIntent(intent);
}

public void method02(){
    int flag = 2;
    Intent intent = new Intent();
    intent.addFlags(flag);
    broadcastIntent(intent);    
}

public void method03(){
    int flag = 3;
    Intent intent = new Intent();
    intent.addFlags(flag);
    broadcastIntent(intent);
}

and this is my broadcastIntent method

public void broadcastIntent(Intent intent){
    sendBroadcast(intent);
}

in my onReceive method i use getFlags() method to get the flag value from the intent and send it through a if, else. but this do not work. any suggestion for improvements are welcome.


Solution

  • I found out the way to this and thought of sharing the code. this is the broadcasting done in my main activity for 2 different methods.

    public void method1(View view){
        Intent intent = new Intent();
        intent.setAction("method1");
        sendBroadcast(intent);
    }
    
    public void method2(View view){
        Intent intent = new Intent();
        intent.setAction("method2");
        sendBroadcast(intent);
    }
    

    and this is how i receive it..

    public class Receiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Broadcast Intent Detected.",Toast.LENGTH_LONG).show();
    }
    

    this is how i registered it on manifest.

     <receiver android:name="Receiver" >
            <intent-filter>
                <action android:name="method1" >
                </action>
                <action android:name="method2" >
                </action>
            </intent-filter>
        </receiver>
    

    Hope this will help if any one else came up with similar problem. and big thank you to every one who posted their answers here.