Shared preferences not setting boolean inside boot_received broadcast receiver

有些话、适合烂在心里 提交于 2019-12-13 04:42:15

问题


I am trying to create the option to start my service on boot. The broadcast receiver works great by itself, but when I add in the option it never sets it to true. Here is the code.

public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
      SharedPreferences prefs = context.getSharedPreferences("startatboot",0);
      boolean startatboot = prefs.getBoolean("startatboot", false);
      if (startatboot) {
          context.startService(new Intent(context, MyService.class));
      }

回答1:


I had to change this...

SharedPreferences prefs = context.getSharedPreferences("startatboot",0);

to this...

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);



public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
      boolean startatboot = prefs.getBoolean("startatboot", false);
      if (startatboot) {
          context.startService(new Intent(context, MyService.class));
      }


来源:https://stackoverflow.com/questions/22261678/shared-preferences-not-setting-boolean-inside-boot-received-broadcast-receiver

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