Android的全局变量不工作在服务 [英] Android global variable not working in Service

查看:130
本文介绍了Android的全局变量不工作在服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑,为什么我无法从我的服务访问我的全局变量。我可以从其他活动访问它们就好了......

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

全局变量类:

public class Global extends Application {
private static final String TAG = "Global Class";

int test;     

public int getTest()
{
    return test;
}

主要活动我用这个测试code:

Main Activity I use this test code:

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

结果是555

Result is 555

我用同样的code另一项活动:

Another activity I use the same code:

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

结果是555

Result is 555

终于在我的服务,我用同样的code如上:

FInally in my service, I use the same code as above:

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

和我得到的又大又肥0了。

and I get big, fat 0 back.

请帮忙。我已经花了3小时这个至今。 我已经尝试过使用getApplication和getApplicationContext

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

此外,清单如下:

...
<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的 - 全局变量

推荐答案

您服务,远程,因为你有这个运行:

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

android:process=":MyService"

在该服务的清单定义。

这意味着,它在运行一个完全独立的过程。使用静态变量的方式不能共享全局变量。

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.

这篇关于Android的全局变量不工作在服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆