Interaction between Activity and Sticky Service

2019-08-29 04:40发布

问题:

i have an Activity and a Sticky Service. The Activity needs to show some values in it´s UserInterface depending on the values of the Sticky Service. So whenever the Service changes his data, the Activity needs to update it´s UserInterface. But how should the Service notify the Activity to change it´s values??

Please remind that the Activity sometimes isn´t alive, only the Service is Sticky.

回答1:

Use LocalBroadcasts

in your service class:

public class LocalMessage extends IntentService{
    private Intent broadcast;
    public static final String BROADCAST = "LocalMessage.BROADCAST";
    public LocalMessage(String name) {
        super(name);
        broadcast = new Intent(name);
    }

@Override
    protected void onHandleIntent(Intent intent) {
        if (broadcast != null) LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);
    }
}

and here is method inside service to broadcast

private void sendLocalMessage(){
    (new LocalMessage(LocalMessage.BROADCAST)).onHandleIntent(null);
}

In your activity:

    private void registerBroadcastReciever() {
        IntentFilter filter = new IntentFilter(YourService.LocalMessage.BROADCAST);
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(receiver, filter);
    } 
    private BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
//doSmth
                }
            };

in your activity onDestroy() method unregister receiver;