Broadcast receiver - monitoring the Battery Level and Charging State

前端 未结 7 2084
逝去的感伤
逝去的感伤 2020-12-31 23:40

I am trying to make two toasts: one when the device is charging, and one when it`s not. But the receiver acting crazy, sending many toasts, and crashing the app. I can not f

7条回答
  •  隐瞒了意图╮
    2021-01-01 00:16

    I found a great way to check if the device is charging, or not. Here is the code of the receiver class:

    public class PowerConnectionReceiver extends BroadcastReceiver {
    
        public PowerConnectionReceiver() {
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
                Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show();
            } else {
                intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
                Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();
            }
        }
    
    
    }
    

    Registering it on onResume:

    receiver = new PowerConnectionReceiver();
    
        IntentFilter ifilter = new IntentFilter();
        ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
        ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        registerReceiver(receiver, ifilter);
    

    Unregistered on onPause:

            unregisterReceiver(receiver);
    

    Works fine!

提交回复
热议问题