我很困惑为什么我不能从我的服务访问我的全局变量。我可以从其他 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:process=":MyService"
在服务的 list 定义中。
这意味着它正在运行一个完全独立的进程。您不能以这种方式使用静态变量共享全局变量。
如果您不需要您的服务在单独的进程中运行,那么只需删除“android:process”行就可以了。
关于Android 全局变量在服务中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11381966/