Android global variable not working in service

I wonder why I cannot access my global variables from my service. I can access them from other events just fine.

global class var:

public class Global extends Application { private static final String TAG = "Global Class"; int test; public int getTest() { return test; } 

Main activity I use this test code:

 Global appState = ((Global)getApplication()); //Context()); appState.setTest(555); Log.e("SETTEST",new Integer(appState.getTest()).toString()); 

Result - 555

In another action, I use the same code:

 Global appState = ((Global)getApplication()); //Context()); Log.e("SETTEST",new Integer(appState.getTest()).toString()); 

Result - 555

In my service, I use the same code as above:

 Global appState = ((Global)getApplication()); //Context()); Log.e("SETTEST",new Integer(appState.getTest()).toString()); 

and I get a big, bold 0 back.

Please, help. I spent 3 hours on it. I tried using getApplication and getApplicationContext

In addition, the manifest is as follows:

 ... <application android:icon="@drawable/signal" android:label="@string/app_ name" android:name="<absolute path>.util.Global"> <service android:name=".util.MyService" android:process=":MyService" android:icon="@drawable/airplane" android:label="@string/service_name" > </service> 

** I just tried using a singleton class, and also according to this post. same problems as above:

Android - global variables?

+5
source share
1 answer

The service works remotely because you have this:

 android:process=":MyService" 

in the manifest definition for the service.

This means that it performs a completely separate process. You cannot share global variables using static variables.

If you do not need your service to run in a separate process, just delete the line "android: process" and you will be fine.

+16
source

All Articles