Broadcast receiver - monitoring the Battery Level and Charging State

前端 未结 7 2086
逝去的感伤
逝去的感伤 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

    If you dont want to use the broadcast on your activity, you can use in a service!!

    Example:

    public class batteryChangeService extends Service {
    
        private BroadcastReceiver mBatteryStateReceiver = new BroadcastReceiver() {
            @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();
                }
            }
        };
    
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            IntentFilter ifilter = new IntentFilter();
            ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
            ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
            registerReceiver(mBatteryStateReceiver, ifilter);
        }
    
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("LocalService", "Received start id " + startId + ": " + intent);
    
            return START_NOT_STICKY;
        }
    
        @Override
        public void onDestroy() {
            unregisterReceiver(mBatteryStateReceiver);
        }
    
    
    }
    

    Register the service in your manifest:

    <service
                android:enabled="true"
                android:name="NAME.COMPANY.APPLICATION.batteryChangeService"
                android:exported="true"/>
    

    In fact, you can use any BroadcastReceiver inside a service!

    0 讨论(0)
提交回复
热议问题