Send data about charging between broadcast and activity with Shared Preferences [android]

雨燕双飞 提交于 2019-12-11 04:26:51

问题


I'm using BroadcastReceiver to send information about status of battery charging to my Main Activity. App uses SharedPreferences to send data.

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?

This is my BroadcastReceiver class:

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;

        }
}

And this is Main Activity:

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

Thanks for your answers


回答1:


Initialise pref like

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

in your BroadcastReceiver inside onReceive()..



来源:https://stackoverflow.com/questions/23662727/send-data-about-charging-between-broadcast-and-activity-with-shared-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!