Sobes.tech
Junior

How do you connect a BroadcastReceiver to receive messages?

sobes.tech AI

Answer from AI

There are two methods:

  1. Statically in the manifest:

    <application ...>
        <receiver android:name=".MyBroadcastReceiver">
            <intent-filter>
                <action android:name="com.example.MY_ACTION" />
                </intent-filter>
        </receiver>
    </application>
    

    — Created at application startup, even if it is not active. — Less flexible but reliable for system events.

  2. Dynamically in code:

    // In an activity or service
    IntentFilter filter = new IntentFilter("com.example.MY_ACTION");
    MyBroadcastReceiver receiver = new MyBroadcastReceiver();
    registerReceiver(receiver, filter);
    
    // Don't forget to unregister when necessary
    // unregisterReceiver(receiver);
    

    — Created and registered at runtime. — More flexible, suitable for in-app events. — Must manually unregister to avoid memory leaks.

How do you connect a BroadcastReceiver to receive… - sobes.tech