我使用BroadcastReceiver
向我的主要活动发送有关电池充电状态的信息。应用使用SharedPreferences
发送数据。
问题在于我的手机连接或断开连接以进行充电。该应用程序崩溃了。我认为这是SharedPreferences
的问题。我对吗?我应该做些什么来搞定?
这是我的BroadcastReceiver
课程:
public class PowerConnectionReceiver extends BroadcastReceiver {
SharedPreferences pref;
public void onReceive(Context context, Intent intent) {
SharedPreferences.Editor prefEditor = pref.edit();
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
prefEditor.putBoolean("isCharging", false).commit();
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
}
}
这是主要活动:
SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("StatusOfCharging", Activity.MODE_PRIVATE);
Boolean isCharging = pref.getBoolean("isCharging", false);
if (isCharging == true){
Toast.makeText(this, "work", Toast.LENGTH_LONG).show();
}else
Toast.makeText(this, "Don't work", Toast.LENGTH_LONG).show();
}
感谢您的回答
答案 0 :(得分:3)
初始化pref
,如
pref = context.getSharedPreferences("StatusOfCharging",context.MODE_PRIVATE);
在你的BroadcastReceiver
内onReceive()
..