Android 从服务到活动的沟通
我以以下方式启动活动中的服务。服务启动后,我关闭活动。如果我再次开始活动,我希望从服务处收到一些信息。我该怎么做Android 从服务到活动的沟通,android,android-intent,Android,Android Intent,我以以下方式启动活动中的服务。服务启动后,我关闭活动。如果我再次开始活动,我希望从服务处收到一些信息。我该怎么做 // Activity @Override public void onCreate(Bundle savedInstanceState) { // here I want to receive data from Service } Intent i=new Intent(this, AppService.class); i.putExtra(AppService.T
// Activity
@Override
public void onCreate(Bundle savedInstanceState)
{
// here I want to receive data from Service
}
Intent i=new Intent(this, AppService.class);
i.putExtra(AppService.TIME, spinner_time.getSelectedItemPosition());
startService(i);
// Service
public class AppService extends Service {
public static final String TIME="TIME";
int time_loud;
Notification note;
Intent i;
private boolean flag_silencemode = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
time_loud = intent.getIntExtra(TIME, 0);
play(time_loud);
return(START_NOT_STICKY);
}
现在最简单的解决方案IMHO是使用第三方事件总线,如(使用
@Producer
允许活动获取给定类型的最后发送事件)或(使用粘性事件允许活动获取给定类型的最后发送事件)。现在最简单的解决方案IMHO,是使用第三方事件总线,如(使用@Producer
允许活动获取给定类型的最后发送事件)或(使用粘性事件允许活动获取给定类型的最后发送事件)。我建议使用Square中的库
Otto是一个事件总线,设计用于解耦您的系统的不同部分
应用程序,同时仍然允许他们高效地通信
简单的方法是创建一个总线:
Bus bus = new Bus();
然后您只需发布一个事件:
bus.post(new AnswerAvailableEvent(42));
订阅了您的服务
@Subscribe public void answerAvailable(AnswerAvailableEvent event) {
// TODO: React to the event somehow!
}
然后服务将提供一个结果
@Produce public AnswerAvailableEvent produceAnswer() {
// Assuming 'lastAnswer' exists.
return new AnswerAvailableEvent(this.lastAnswer);
}
我建议使用广场图书馆
Otto是一个事件总线,设计用于解耦您的系统的不同部分
应用程序,同时仍然允许他们高效地通信
简单的方法是创建一个总线:
Bus bus = new Bus();
然后您只需发布一个事件:
bus.post(new AnswerAvailableEvent(42));
订阅了您的服务
@Subscribe public void answerAvailable(AnswerAvailableEvent event) {
// TODO: React to the event somehow!
}
然后服务将提供一个结果
@Produce public AnswerAvailableEvent produceAnswer() {
// Assuming 'lastAnswer' exists.
return new AnswerAvailableEvent(this.lastAnswer);
}
与其使用第三方解决方案,为什么不直接使用LocalBroadcasts呢?@Waqas:对于事件传递,
LocalBroadcastManager
可以。但是,对于拉取事件,LocalBroadcastManager
中没有等效于Otto的@Producer
或EventBus的粘性事件。但是上下文呢。sendStickyBroadcast
?@Waqas:这不是本地广播。这包括IPC,还有一个额外的权限发送粘性广播
。谢谢您的回答。是否有一种方法可以从活动中调用函数或其他内容?因为我总是让服务运行,也许我可以从Activity访问服务??而不是使用第三方解决方案,为什么不简单地使用LocalBroadcasts?@Waqas:对于事件传递,LocalBroadcastManager
。但是,对于拉取事件,LocalBroadcastManager
中没有等效于Otto的@Producer
或EventBus的粘性事件。但是上下文呢。sendStickyBroadcast
?@Waqas:这不是本地广播。这包括IPC,还有一个额外的权限发送粘性广播
。谢谢您的回答。是否有一种方法可以从活动中调用函数或其他内容?因为我总是让服务运行,也许我可以从Activity访问服务??