我正在尝试创建启动时启动服务的选项。广播接收器本身很好用,但是当我添加选项时,它永远不会将其设置为真。这是代码。
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));
}
答案 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));
}