使用共享首选项发送有关广播和活动之间收费的数据[android]

时间:2014-05-14 18:48:09

标签: android broadcastreceiver sharedpreferences

我使用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();
    }

感谢您的回答

1 个答案:

答案 0 :(得分:3)

初始化pref,如

pref = context.getSharedPreferences("StatusOfCharging",context.MODE_‌​PRIVATE);

在你的BroadcastReceiveronReceive() ..