Android自定义类 - Hook into Activity Lifecycle

时间:2017-01-22 21:16:16

标签: android android-activity lifecycle

我有一项活动,我希望监控电池寿命。我想把电池寿命分成它自己的班级。我可以在活动

中执行以下操作
onPause() {
  batteryChecker = new BatteryChecker();
}
onResume() {
   batteryChecker.kill();
}

我更愿意这样做:

onCreate() {
  bg = new BatteryChecker(this);
}

有什么方法可以让BatteryChecker响应附加活动的onPause / onResume?

2 个答案:

答案 0 :(得分:2)

当您创建BatteryChecker课程时,ActivityLifecycleCallbacks可以实施registerActivityLifecycleCallbacks并致电onCreate Application,在这种情况下,您的自定义课程将会收到所有活动生命周期回调。

在此处查看更多内容 - ActivityLifecycleCallbacks

答案 1 :(得分:0)

你需要一个类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;
        }
    }

更多信息。 Monitoring Battery State