本文介绍了发送有关使用共享preferences [机器人]广播和活动之间的计费数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用广播接收器
发送关于电池的充电状态我的主要活动的信息。应用程序使用共享preferences
发送数据。
I'm using BroadcastReceiver
to send information about status of battery charging to my Main Activity. App uses SharedPreferences
to send data.
在我的手机连接或断开充电的问题。这款应用程序崩溃。我觉得这是问题,共享preferences
。我对吗?而我应该做的工作中取得好?
The problem is when my phone is connected or disconnected to charge. The app is crashed. I think this is problem with SharedPreferences
. Am i right? And what i should do to get in working well?
这是我的广播接收器
类:
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();
}
谢谢您的回答
推荐答案
初始化 preF
像
pref = context.getSharedPreferences("StatusOfCharging",context.MODE_PRIVATE);
在广播接收器
在的onReceive()
..
这篇关于发送有关使用共享preferences [机器人]广播和活动之间的计费数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!