Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android global variable not working in Service

I'm perplexed why I cannot access my global variables from my service. I can access them from other activities just fine....

global var class:

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 is 555

Another activity I use the same code:

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

Result is 555

FInally 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 big, fat 0 back.

Please help. I've spent 3 hours on this so far. I've tried using getApplication, and getApplicationContext

Also, manifest looks like this:

...
<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 as well according to this post. same troubles as above:

Android - Global variables?

like image 689
The Cure Avatar asked Jul 08 '12 09:07

The Cure


1 Answers

Your service is running remotely because you've got this:

android:process=":MyService"

in the manifest definition for the service.

This means that it is running an a completely separate process. You can't share global variables using static variables that way.

If you don't need your service to run in a separate process, then just remove the "android:process" line and you'll be good.

like image 61
David Wasser Avatar answered Sep 28 '22 19:09

David Wasser