如何从另一个对象访问服务内的变量

时间:2013-11-14 16:20:36

标签: java android object service reference

我有一项收集传感器数据的服务。 该服务在一个类中启动,我们称之为x。在x内部,我在 webview 中为JavaScript界面​​定义了一些方法。

现在我需要在x中获取该数据以将其注入webview以将其发布到服务器。 这是什么最好的做法?

如何在x中获取对服务实例的引用,以便我可以访问其方法和属性?

2 个答案:

答案 0 :(得分:2)

我知道有两种方法可以做到。 将您的服务声明为单例并实现访问变量的方法。

YourService.getInstance().getVariable();

但我不建议使用这种方法。

另一种方法是使用Android提供的活页夹系统。

您活动中的代码。

private YourService yourService;
private boolean serviceBound = false;
private ServiceConnection serviceConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName cn, IBinder ib) {
        yourService = ((YourService.ServiceBinder) ib).getInfo();
        serviceBound = true;
    }

    public void onServiceDisconnected(ComponentName cn) {
        serviceBound = false;
    }
};

然后,您可以在yourService对象上调用服务中实现的方法。

您还必须在服务中实现这样的活页夹。

public class ServiceBinder extends Binder {

    public YourService getInfo() {
        return YourService.this;
    }
}

希望它有所帮助。

答案 1 :(得分:2)

不确定它是否是最佳方式,但我最近通过使用应用程序结构解决了这个问题。

创建一个类。

public class myApp extends Application {
    public int yourData;
}

然后使用以下代码从程序中的任何活动进行访问。

myApp app = (myApp) getApplication();
int localVar = app.yourData;

不要忘记更新Android Manifest

    <application
    android:name="myApp"