我正在开发一个 android 应用程序,它创建一个 android 服务,使用 gps 刷新移动设备的位置。它与一个计时器一起工作,在“x”时间内刷新位置。
问题是我想通过应用程序的一个 Activity 与本地 android 服务通信,因为我想在需要时更改刷新时间 ('x')。那么,我该怎么做呢?
一种可能的解决方案是在每次刷新时间改变时停止服务然后重新启动,但我认为这不是最佳解决方案。
有什么建议,帮助吗?
最佳答案
如果您在同一进程空间(同一应用程序/.apk)中,您可以建立一个简单的服务连接 在您的 Activity 中,包括如下内容:
private ServiceConnection _svcConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName arg0) {
_myService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
_myService = ((MyService.LocalBinder) service).getService();
if(!_myService.IsRunning())
_myService.Start();
}
};
@Override
protected void onResume() {
bindService(new Intent(Main.this, MyService.class), _svcConnection
BIND_AUTO_CREATE);
startService(new Intent(Main.this, MyService.class));
super.onResume();
}
@Override
protected void onPause() {
unbindService(_svcConnection);
super.onPause();
}
您的服务需要一个 Binder :
private final IBinder _Binder = new LocalBinder();
@Override
public IBinder onBind(Intent arg0) {
return _Binder;
}
/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
然后您可以使用 _MyService 对象并调用其上的任何方法。 (例如注册回调或请求位置更新),但请注意,如果服务连接失败,_MyService 变量将为空!
_MyService.SetInterval(4);
如果你需要从另一个应用程序(另一个进程)访问这个服务,你必须处理IPC。
关于android - 与安卓服务通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7819627/