Android Would Like Your Attention
new Thread(threadBody).start();
registerReceiver(onBatteryChanged,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
We set the receiver's IntentFilter to watch for ACTION_BATTERY_CHANGED
events, routing them to an onBatteryChanged object.
You will need to add an import for android.content.IntentFilter.
Next, call unregisterReceiver() in onDestroy() in PostMonitor:
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(onBatteryChanged);
active.set(false);
}
If we do not do this, our service will keep running and getting battery
events even after it would ordinarily have shut down.
Both of these rely on an onBatteryChanged BroadcastReceiver
implementation, which you should add to PostMonitor:
BroadcastReceiver onBatteryChanged=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int pct= 100
*intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 1 )
/intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1 );
isBatteryLow.set(pct<= 25 );
}
};
All we do is examine the battery level (as measured on the battery level
scale) and, if it hits 25% or lower, we set an isBatteryLow object to true;
otherwise, we set it to false.