How to access a variable present in a service

2019-08-07 03:25发布

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

Can anyone give an idea?

3条回答
We Are One
2楼-- · 2019-08-07 04:15

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.

查看更多
相关推荐>>
3楼-- · 2019-08-07 04:17

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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-08-07 04:23

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);
查看更多
登录 后发表回答