安卓:从我正在运行的服务获得一个变量 [英] Android: Getting a variable from my running service

查看:207
本文介绍了安卓:从我正在运行的服务获得一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的活动开始服务,而当我关闭我的应用程序,该服务将继续运行。
OK,这是正确的。但是,当我再次打开我的应用程序,在活动中,我需要知道,我已经开始pviously $ P $上运行的服务(类)中定义的公共变量的值。

My activity starts a Service, and when I close my app, the service continues to run. OK, that's right. But when I open my application again, in the activity, I need to know the value of a public variable defined on the running Service(class) that I've started previously.

我怎么能这样做?

感谢

推荐答案

如果您在您的活动绑定到服务,你应该在文件夹接口的实现你的服务,例如:

If you are binding your Activity to the Service, you should have an implementation of the Binder interface in your Service, e.g.

public class ServiceBinder extends Binder {
    public MyService getService() {
        return MyService.this;
    }
}

在您的活动中,创建​​一个新的 ServiceConnection 类将被用来给您访问服务:

In your Activity, create a new ServiceConnection class which will be used to give you access to your Service:

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMyService = ((MyService.ServiceBinder)service).getService();
    }

    public void onServiceDisconnected(ComponentName className) {
        mMyService = null;
    }
};

下面的成员变量 mMyService 会给你访问你的服务类的所有公共成员。

Here the member variable mMyService will give you access to all public members of your Service class.

要创建连接,实施 doBindService doUnbindService 在你的活动:

To create the connection, implement doBindService and doUnbindService in your Activity:

void doBindService() {
    bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
}

void doUnbindService() {
    // Detach our existing connection.
    unbindService(mConnection);
}

希望这有助于!

这篇关于安卓:从我正在运行的服务获得一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆