I have an activity in which I want to monitor battery life. I want to decouple the battery life into it's own class. I could do the following in the activity
onPause() {
batteryChecker = new BatteryChecker();
}
onResume() {
batteryChecker.kill();
}
I would prefer to just do this:
onCreate() {
bg = new BatteryChecker(this);
}
Is there any way I can get BatteryChecker to respond to the onPause/onResume of the attached activity?
Your BatteryChecker
can implement ActivityLifecycleCallbacks
and call registerActivityLifecycleCallbacks
in onCreate
when you create your Application
class, in this case your custom class will receive all Activity lifecycle callbacks.
see more here - ActivityLifecycleCallbacks
It's of arguable benefit because you still have to use Activity
events, but you could attach to the Activity
lifecycle in your activity's onCreate()
and detach from it in its onDestroy()
events too.
This may help from a hygiene perspective depending on how "busy" your code is in its existing lifecycle blocks, but doesn't necessarily make it a good practice.
In your BatteryChecker
class:
public class BatteryChecker implements Application.ActivityLifecycleCallbacks {
private boolean paused = true ;
...
@Override
public void onActivityResumed(@NonNull Activity activity) {
if (paused) doResumeStuff();
paused = false;
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
if (!paused) doPauseStuff();
paused = true;
}
}
And in your activity:
private BatteryChecker batteryChecker = null;
@Override
public void onCreate(final Bundle savedInstanceState) {
batteryChecker = new BatteryChecker();
getApplication().registerActivityLifecycleCallbacks(batteryChecker);
}
@Override
public void onDestroy() {
getApplication().unRegisterActivityLifecycleCallbacks(batteryChecker);
}
It should also be noted you'll never see the onActivityDestroyed()
event fire in your BatteryChecker
class as its scope is within that of the actual activity's lifecycle.
You need a class extends broadcastReceiver
public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
}
}
more info. Monitoring Battery State
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.