I'm looking for a way of executing a piece of code within my Android application when the phone reaches 10% battery life. Would anyone be able to point me in the right direction of how to do so?
Write one receiver for getting the battery level like this:
public class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
if (level < 10) {
// Write your code here
}
}
}
Write One Service:
public class BatteryService extends Service {
private BatteryReceiver receiver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
receiver = new BatteryReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
Register this service in your Manifest file like this:
<service android:name="com.example.testandroid.BatteryService" >
</service>
then start the service in First Activity is Enough.