Using a broadcast intent/broadcast receiver to send messages from a service to an activity

前端 未结 4 1130
轻奢々
轻奢々 2020-12-02 06:32

So I understand (I think) about broadcast intents and receiving messages to them.

So now, my problem/what I can\'t work out is how to send a message from the o

4条回答
  •  旧巷少年郎
    2020-12-02 07:08

    EDITED Corrected code examples for registering/unregistering the BroadcastReceiver and also removed manifest declaration.

    Define ReceiveMessages as an inner class within the Activity which needs to listen for messages from the Service.

    Then, declare class variables such as...

    ReceiveMessages myReceiver = null;
    Boolean myReceiverIsRegistered = false;
    

    In onCreate() use myReceiver = new ReceiveMessages();

    Then in onResume()...

    if (!myReceiverIsRegistered) {
        registerReceiver(myReceiver, new IntentFilter("com.mycompany.myapp.SOME_MESSAGE"));
        myReceiverIsRegistered = true;
    }
    

    ...and in onPause()...

    if (myReceiverIsRegistered) {
        unregisterReceiver(myReceiver);
        myReceiverIsRegistered = false;
    }
    

    In the Service create and broadcast the Intent...

    Intent i = new Intent("com.mycompany.myapp.SOME_MESSAGE");
    sendBroadcast(i);
    

    And that's about it. Make the 'action' unique to your package / app, i.e., com.mycompany... as in my example. This helps avoiding a situation where other apps or system components might attempt to process it.

提交回复
热议问题