Question

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

Était-ce utile?

La solution

Initialise pref like

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

in your BroadcastReceiver inside onReceive()..

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top