共享首选项未在boot_received广播接收器中设置布尔值

时间:2014-03-07 22:09:57

标签: android broadcastreceiver

我正在尝试创建启动时启动服务的选项。广播接收器本身很好用,但是当我添加选项时,它永远不会将其设置为真。这是代码。

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 个答案:

答案 0 :(得分:1)

我不得不改变这个......

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

到此......

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));
      }