Search code examples
androidbattery

Android Battery Level Notification & after 5 mins shutdown/Power Off the Device


I have Android application which is Sales Rep application.When he using the app first need to show the notification like your battery level is 10% ..., then after 2 minutes if he doesn't plug the power , it automatically need to shut down the device.

I have created like this

     public class BatteryLevelActivity extends BroadcastReceiver{

     @Override
     public void onReceive(Context context, Intent intent) {
        int level = intent.getIntExtra("level", 0);  
            Toast.makeText(context, "Battery Level is "+level+"%", Toast.LENGTH_LONG) ;

    }
}

And My androidManifest File

       <receiver android:name=".service.BatteryLevelActivity">
         <intent-filter>
            <action android:name="android.intent.action.BATTERY_CHANGED" />
        </intent-filter>
    </receiver> 

And Calling place i did like this

     batteryLevelReceiver = new BatteryLevelReceiver();
    IntentFilter intentFilter1 = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    intentFilter1.addAction(Intent.ACTION_BATTERY_LOW);
    registerReceiver(batteryLevelReceiver, intentFilter1);

It go to BatteryLevelReceiver class. I really don't know How to check power is plugged or not && how to power off automatically after showing the notification ?

Please anybody help me on this ...

Thanks in advance..


Solution

  • To check that the device is plugged in or not you can try this stuff,

    public static boolean isConnected(Context context) {
            Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
        }
    

    For shutting down device here is a thread that you will like to check and for checking the plugged in status already posted the method from this thread.