Using Activity class static members in a background service

╄→尐↘猪︶ㄣ 提交于 2019-12-25 14:49:27

问题


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?

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


回答1:


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.

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.




回答2:


Because prefsdefault is NULL. I don't see that it is initialized. You can do that by

prefsdefault = getSharedPreferences("my_preferences", Activity.MODE_PRIVATE);

Hot tip: Never make your SharedPreference instance static.




回答3:


The reason for this is SharedPreferences is not initialised u dont need to do like this as SharedPreferences are global available with in app if MODE is Private just create new instance in service as well it will work



来源:https://stackoverflow.com/questions/15325882/using-activity-class-static-members-in-a-background-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!