Android 全局变量在服务中不起作用

标签 android global-variables

我很困惑为什么我不能从我的服务访问我的全局变量。我可以从其他 Activity 中很好地访问它们....

全局变量类:

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

int test;     

public int getTest()
{
    return test;
}

我使用此测试代码的主要 Activity :

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

结果是555

我使用相同代码的另一个 Activity :

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

结果是555

最终在我的服务中,我使用了与上面相同的代码:

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

然后我变大了,胖了 0。

请帮忙。到目前为止,我已经花了 3 个小时。 我试过使用 getApplication 和 getApplicationContext

此外, list 看起来像这样:

...
<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>

** 根据这篇文章,我也尝试使用单例类。和上面一样的麻烦:

Android - Global variables?

最佳答案

你的服务正在远程运行,因为你有这个:

android:process=":MyService"

在服务的 list 定义中。

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

如果您不需要您的服务在单独的进程中运行,那么只需删除“android:process”行就可以了。

关于Android 全局变量在服务中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11381966/

相关文章:

c++ - 执行静态对象的析构函数时崩溃

无法将全局变量从 dll 导入到应用程序中?

java - 每 5 秒重复一次声音

java - 单击 ListView 将 Firebase 数据从一个 Activity 传递到另一个 Activity

rust - 在 Rust 中,我如何定义一个全局变量/常量,其值是函数的结果?

javascript - 函数不会更新变量

javascript - Var 和 JavaScript 变量作用域

android - 扩展应用程序类和良好实践

java - Activity 线程访问

java - 如何在Android中绘制JButton