user2308321
user2308321

Reputation: 35

How to access variables inside a service from another object

I have a service that collects sensor data. The service is started in a class, lets call it x. Inside x I've defined a few methods for a JavaScript interface in a webview.

now I need to get that data inside x to inject it to the webview to post it to server. what is the best practice for this?

How can I get a reference to the service instance inside x so I can access its methods and properties?

Upvotes: 0

Views: 1995

Answers (2)

mtbomb
mtbomb

Reputation: 1117

Not sure if its the best way or not, but I recently solved this problem by using the Application structure.

Create a class.

public class myApp extends Application {
    public int yourData;
}

Then use the following code to access from any Activity in your program.

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

Don't forget to update your Android Manifest

    <application
    android:name="myApp"

Upvotes: 3

Substitut
Substitut

Reputation: 403

I know two way to do it. Declare your service as a singleton and implement methods to access your variable.

YourService.getInstance().getVariable();

But I wouldn't recommand this method.

The other way is to use binder system provide by Android.

Code in your activity.

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;
    }
};

And then you can call methods implemented in your service on your yourService object.

You also have to implement a binder in your service like this.

public class ServiceBinder extends Binder {

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

Hope it helped.

Upvotes: 3

Related Questions