活动与粘性服务之间的互动

时间:2013-11-02 12:44:00

标签: android service android-activity

我有活动粘性服务。 Activity需要在UserInterface中显示一些值,具体取决于Sticky Service的值。所以每当服务更改他的数据时,Activity需要更新它的UserInterface。 但服务如何通知活动更改其值?

请提醒一下,活动有时并不存在,只有服务是粘性的。

1 个答案:

答案 0 :(得分:0)

使用LocalBroadcasts

在您的服务类中:

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);
    }
}

这里是广播服务的方法

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

在您的活动中:

    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
                }
            };

在您的活动onDestroy()方法中取消注册接收器;