android - 与安卓服务通信

标签 android service android-activity

我正在开发一个 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/

相关文章:

java - 不开始主要 Activity

android - 使用服务进行 BroadcastReceiver 日志记录的替代方法

android - 在 android 中的 ListView 内的按钮上设置 OnClick 监听器

service - 如何在批处理文件中使用 taskkill 终止名称中带有空格的 Windows 服务

C#/.NET : Detect whether program is being run as a service or a console application

java - onRestoreInstanceState() 究竟是如何工作的?

java - Picasso 示例错误/无法编译

Android - 从动态创建的微调器中获取所选项目

java - JavaFX 中具有输入和输出参数的并发后台任务或服务

android - bundle 不工作