Junior — Middle
Kuidas rakendada Broadcast Receiver komponendit, mis töötab ainult praeguse rakenduse raames?
sobes.tech AI
Vastus AI-lt
To ensure that the Broadcast Receiver works only within the current application, it must be registered dynamically via code, not in the manifest. With dynamic registration using registerReceiver(), the receiver will only receive broadcast messages sent within the application.
Example:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// handle event
}
};
// Register in Activity or Service
IntentFilter filter = new IntentFilter("com.example.MY_ACTION");
registerReceiver(receiver, filter);
// Don't forget to unregister
unregisterReceiver(receiver);
This way, you limit the scope of the Broadcast Receiver to the current application, as system or other applications will not be able to send such local broadcast messages.