设备重启后插入应用程序强制关闭

时间:2015-01-01 23:44:41

标签: java android android-intent android-activity android-studio

我有一个具有意图过滤器的广播接收器:ACTION_POWER_CONNECTED。接收器应该启动服务。当设备未重新启动时,接收器工作正常,但是一旦我重新启动设备并插入设备,应用程序强制关闭。在我的接收器中,我引用了另一个活动的静态变量。为什么应用程序强制关闭?

“dataSaved”是MainActivity中的SharedPreferences变量

if (MainActivity.dataSaved.getBoolean("User", false)) {
    Intent i = new Intent(context, BatteryService.class)
    context.startService(i);
}

1 个答案:

答案 0 :(得分:1)

您说dataSaved是静态SharedPreference,未初始化,因此getBoolean会抛出NullPointerException。您在MainActivity中的某个位置初始化了它,但在重新启动后没有MainActivity来初始化它

在接收方

中获取sharedprefernce
SharedPreferences dataSaved = context.getSharedPreferences("prefs",  Context.MODE_PRIVATE);
 boolean isUser = dataSaved.getBoolean("User", false);