Reddy
Reddy

Reputation: 79

How to access a variable present in a service

I want to access a variable present in a service from another service/an activity....

Can anyone give an idea?

Upvotes: 1

Views: 4550

Answers (3)

Slubb
Slubb

Reputation: 515

If what you mean is that you want to access the variable after you close and open the app, then you're probably looking for SharedPreferences. Note that this requires a context (an activity or service).

To store:

int data = 5;
SharedPreferences storage = getSharedPreferences("storage", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = storage.edit();
editor.putInt("myInt", data);
editor.commit();

To get:

SharedPreferences storage = getSharedPreferences("storage", Context.MODE_PRIVATE);
int data = storage.getInt("myInt", 0);

Upvotes: -1

NitroG42
NitroG42

Reputation: 5356

To communicate between two service or activity, you need to use AIDL
It is not really difficult to do, and there is a lot of tutorial like this.

Upvotes: 2

Ovidiu Latcu
Ovidiu Latcu

Reputation: 72331

You can make a public getter for that variable in your Service class, bind to that service, and access the getter to give you that variable.

Upvotes: 1

Related Questions