且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在后台服务中使用Activity类静态成员

更新时间:2022-12-27 09:27:18

这是因为,即使您的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.