문제

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

도움이 되었습니까?

해결책

Initialise pref like

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

in your BroadcastReceiver inside onReceive()..

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top