Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when the Battery's low : Android?

Tags:

java

android

I want to close my app when the battery level of the device gets low. I have added following codes in manifest.

 <receiver android:name=".BatteryLevelReceiver" 
         <intent-filter>
            <action android:name="android.intent.action.ACTION_BATTERY_LOW" />
            <action android:name="android.intent.action.ACTION_BATTERY_OKAY" />
        </intent-filter>
 </receiver>

And following code in receiver

public class BatteryLevelReceiver extends BroadcastReceiver 
{

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Toast.makeText(context, "BAttery's dying!!", Toast.LENGTH_LONG).show();
        Log.e("", "BATTERY LOW!!");
    }
}

I am running the app on emulater and changing the battery level using telnet. It changes the battery level but not showing any toast or logs.

What am I missing? Any help is appreciated!

like image 618
Adarsh H S Avatar asked Nov 05 '12 09:11

Adarsh H S


1 Answers

Register using context register. If you are targeting Android 8.0 or higher, you cannot use manifest declared receiver. Paste this code in your main activity to register.

 BroadcastReceiver receiver = new BatteryLevelReceiver();
        IntentFilter filter =new IntentFilter(BatteryManager.EXTRA_BATTERY_LOW);
        filter.addAction(Intent.ACTION_BATTERY_LOW);
        this.registerReceiver(receiver, filter);

and you are good to go PS the emulator should not be in charging state

like image 107
chris Avatar answered Nov 14 '22 14:11

chris