活动和粘滞服务之间的交互 [英] Interaction between Activity and Sticky Service
问题描述
我有一个活动和置顶服务。该活动需要在it's的UserInterface表现出一定的值取决于置顶服务的价值。因此,每当服务改变了他的数据,该活动需要更新it's的UserInterface。 但如何在服务通知活动以改变it's价值观
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??
请提醒的是,活动有时isn't活着,只有服务的粘性。
Please remind that the Activity sometimes isn´t alive, only the Service is Sticky.
推荐答案
使用LocalBroadcasts
Use 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);
}
}
这里是方法内部服务广播
and here is method inside service to 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()方法注销接收器;
in your activity onDestroy() method unregister receiver;
这篇关于活动和粘滞服务之间的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!