我刚刚开始在Android中使用服务,我制作了一个简单的服务,每20秒轮询一次服务器。
现在我如何从我的主要活动中获取此数据(当它处于活动状态时)?
或者,服务可以将其发送回我的主要活动(但仅在其活动时)。我不想忘记我的活动。
我已阅读“绑定”的SDK examples但我无法找到如何实际从服务中获取内容的示例。如何启动和停止绑定。
从示例中。如果我的活动中有“mBoundService”对象,如何从名为eg的服务方法中获取数据。 “pollingData()”?
答案 0 :(得分:3)
我的建议是使用服务中的sendBroadcast()
发送广播,然后在主要活动中使用BroadcastReceiver
作为内部类。您可以使用putExtras()
和getExtras()
希望这有帮助!
一个实际的例子:
public class x extends Service {
//Code for your service goes here
public talk() {
Intent i = new Intent();
i.putExtras("Extra data name", "Super secret data");
i.setAction("FILTER");
sendBroadcast(i);
}
}
然后在课堂上,服务正在与之交谈:
public class y extends Activity {
//Code for your activity goes here
BroadcastReceiver br = new BroadcastReceiver() {
public void onReceive(Intent i) {
String str = (String) i.getExtras().get("Extra data name").toString();
}
OnResume() {
super.OnResume();
IntentFilter filt = new IntentFilter("FILTER");
this.registerReceiver(br, filt);
//Do your other stuff
}
OnPause() {
super.OnPause();
unregisterReceiver(br);
}
希望这个例子是关于你要找的东西,如果你需要更多的细节,请告诉我。