在后台服务中使用Activity类静态成员 [英] Using Activity class static members in a background service

查看:110
本文介绍了在后台服务中使用Activity类静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序具有一个称为MainActivity的Activity类,其成员之一是

My app has an Activity class called MainActivity and one of its members is

public static SharedPreferences prefsdefault;

我的应用程序还具有在后台运行的服务(在另一个过程中).在我写的服务中

My app has also a service (in another process) which runs in background. Inside the service I wrote

MainActivity.prefsdefault.getString(Key,"Hello");

应用有时会在此行引发空指针异常.为什么?这是否意味着当我关闭活动并且我无法在任何时候(当我的服务运行时)访问它时,垃圾收集器会清理此成员?那么,什么是完美的解决方案呢?

The app sometimes throws null pointer exception at this line. Why? Does it mean that this member is cleaned up by the garbage collector when I close the activity and I cannot access it at anytime (when my service runs)? So what is the perfect solution for this?

我应该将MainActiviy.class传递给服务吗?当我实现需要上下文的线程时,也会发生这种情况.

Should I pass the MainActiviy.class to the service? It also happens when I implement a thread that requires a context.

推荐答案

这是因为,即使您的prefsdefault可能已经初始化过一次,您的整个应用仍可以被垃圾回收并重新启动.

That's because, even if your prefsdefault may have been initialized once, your whole app can be garbage collected and restarted again.

在这种情况下,您的服务将发现该字段为空.在活动中使用静态字段是错误的,原因有很多,最重要的是您的应用可能会被操作系统杀死并重新启动,然后又将所有静态字段清除掉.

In that case your service will find that field as null. Using static fields inside activities is wrong for a bunch of reasons, the most important is that your app may be killed and restarted by the operating system and after that all the static fields are wiped out again.

使用共享首选项的正确方法是在需要访问/写入时使用getSharedPreferences访问它们.

The correct way to use shared preferences is to access them using getSharedPreferences whenever you need to access / write.

另一个奇怪的事情是您说该服务在另一个进程中运行.在这种情况下,它应该无法从另一个进程访问数据.

The other weird thing is that you say that the service runs in another process. In that case it should not be able to access to data from another process.

这篇关于在后台服务中使用Activity类静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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