简体   繁体   English

android服务如何与活动交互

[英]How an android service interact with the activity

I'm developing a subway guide app, when reaching a new station, a notification will pop up, and the map shown in the main activity will refresh. 我正在开发一个地铁指南应用程序,当到达新站时,会弹出一个通知,主活动中显示的地图将刷新。 I put the guide code in a service so that users can run other apps while being guided. 我将指南代码放在一个服务中,以便用户可以在被引导的同时运行其他应用程序。 But the main activity needs to be refreshed when reaching a new station, how can the service make some changes to the view in the main activity? 但是当到达新站时,主要活动需要刷新,服务如何对主要活动中的视图进行一些更改?

In your activity, you should register a receiver 在您的活动中,您应该注册接收者

Declare the receiver first 首先声明接收器

public class ReceiverTest extends BroadcastReceiver
{
  @Override
  public void onReceive(Context context, Intent intent)
  {
     // extras from service
     int key = intent.getIntExtra("key", 0);

     //do things here
  }
}

Register it in OnCreate of your activity 在活动的OnCreate中注册

ReceiverTest mReceiver = new ReceiverTest();
IntentFilter filter;
filter = new IntentFilter("packagename.dosomething");
registerReceiver(mReceiver, filter);

Then, in your service, broadcast the event 然后,在您的服务中,广播该事件

Intent i = new Intent("packagename.dosomething");
// You could put the information in extras, then get the value in receiver
i.putExtra("key", 123);
context.sendBroadcast(i);

There are a couple of ways to do this. 有几种方法可以做到这一点。 You can bind the service with the activity. 您可以将服务与活动绑定。 You can send broadcast messages to the activity (the activity need to register with the Broadcast Reciever) There are lot of discussions on this topic. 您可以向活动发送广播消息(活动需要向广播接收者注册)有很多关于此主题的讨论。 You can go through them. 你可以通过他们。

The best way to share data between the Service S and Activity A 在服务S和活动A之间共享数据的最佳方式

Use the local binding pattern and have Activity A bind to Service S, then call the service's exposed API to retrieve whatever is needed. 使用本地绑定模式并将Activity A绑定到Service S,然后调用服务的公开API以检索所需的任何内容。

How can the external activity B communicate with the Service S to determine if it has completed with all its preprocessing, and the Activity A is ready to be invoked? 外部活动B如何与服务S通信以确定它是否已完成所有预处理,并且活动A已准备好被调用?

Use the remote binding pattern and AIDL. 使用远程绑定模式和AIDL。 Activity B would register an AIDL-defined callback with Service S, which the service would invoke when appropriate. 活动B将使用服务S注册AIDL定义的回调,服务将在适当时调用。 See here and here for an example. 在这里这里看一个例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM