Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 2139276c authored by Jeff Brown's avatar Jeff Brown
Browse files

Refactor BatteryService to new pattern.

Apply SystemService pattern to BatteryService.

Change-Id: I4971b2da8d2aed4d14440fb65863a8b916bab03c
parent 2c43c339
Loading
Loading
Loading
Loading
+49 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.os;

/**
 * Battery manager local system service interface.
 *
 * @hide Only for use within the system server.
 */
public abstract class BatteryManagerInternal {
    /**
     * Returns true if the device is plugged into any of the specified plug types.
     */
    public abstract boolean isPowered(int plugTypeSet);

    /**
     * Returns the current plug type.
     */
    public abstract int getPlugType();

    /**
     * Returns battery level as a percentage.
     */
    public abstract int getBatteryLevel();

    /**
     * Returns whether we currently consider the battery level to be low.
     */
    public abstract boolean getBatteryLevelLow();

    /**
     * Returns a non-zero value if an unsupported charger is attached.
     */
    public abstract int getInvalidCharger();
}
+87 −76
Original line number Diff line number Diff line
@@ -18,6 +18,7 @@ package com.android.server;

import android.database.ContentObserver;
import android.os.BatteryStats;

import com.android.internal.app.IBatteryStats;
import com.android.server.am.BatteryStatsService;
import com.android.server.lights.Light;
@@ -29,6 +30,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.BatteryManager;
import android.os.BatteryManagerInternal;
import android.os.BatteryProperties;
import android.os.Binder;
import android.os.FileUtils;
@@ -83,7 +85,7 @@ import java.io.PrintWriter;
 * service asynchronously itself.
 * </p>
 */
public final class BatteryService extends Binder {
public final class BatteryService extends SystemService {
    private static final String TAG = BatteryService.class.getSimpleName();

    private static final boolean DEBUG = false;
@@ -140,10 +142,12 @@ public final class BatteryService extends Binder {

    private boolean mSentLowBatteryBroadcast = false;

    public BatteryService(Context context, LightsManager lightsManager) {
    public BatteryService(Context context) {
        super(context);

        mContext = context;
        mHandler = new Handler(true /*async*/);
        mLed = new Led(context, lightsManager);
        mLed = new Led(context, getLocalService(LightsManager.class));
        mBatteryStats = BatteryStatsService.getService();

        mCriticalBatteryLevel = mContext.getResources().getInteger(
@@ -160,7 +164,10 @@ public final class BatteryService extends Binder {
            mInvalidChargerObserver.startObserving(
                    "DEVPATH=/devices/virtual/switch/invalid_charger");
        }
    }

    @Override
    public void onStart() {
        IBinder b = ServiceManager.getService("batteryproperties");
        final IBatteryPropertiesRegistrar batteryPropertiesRegistrar =
                IBatteryPropertiesRegistrar.Stub.asInterface(b);
@@ -169,9 +176,14 @@ public final class BatteryService extends Binder {
        } catch (RemoteException e) {
            // Should never happen.
        }

        publishBinderService("battery", new BinderService());
        publishLocalService(BatteryManagerInternal.class, new LocalService());
    }

    void systemReady() {
    @Override
    public void onBootPhase(int phase) {
        if (phase == PHASE_ACTIVITY_MANAGER_READY) {
            // check our power situation now that it is safe to display the shutdown dialog.
            synchronized (mLock) {
                ContentObserver obs = new ContentObserver(mHandler) {
@@ -189,8 +201,9 @@ public final class BatteryService extends Binder {
                updateBatteryWarningLevelLocked();
            }
        }
    }

    void updateBatteryWarningLevelLocked() {
    private void updateBatteryWarningLevelLocked() {
        final ContentResolver resolver = mContext.getContentResolver();
        int defWarnLevel = mContext.getResources().getInteger(
                com.android.internal.R.integer.config_lowBatteryWarningLevel);
@@ -207,15 +220,6 @@ public final class BatteryService extends Binder {
        processValuesLocked(true);
    }

    /**
     * Returns true if the device is plugged into any of the specified plug types.
     */
    public boolean isPowered(int plugTypeSet) {
        synchronized (mLock) {
            return isPoweredLocked(plugTypeSet);
        }
    }

    private boolean isPoweredLocked(int plugTypeSet) {
        // assume we are powered if battery state is unknown so
        // the "stay on while plugged in" option will work.
@@ -234,34 +238,7 @@ public final class BatteryService extends Binder {
        return false;
    }

    /**
     * Returns the current plug type.
     */
    public int getPlugType() {
        synchronized (mLock) {
            return mPlugType;
        }
    }

    /**
     * Returns battery level as a percentage.
     */
    public int getBatteryLevel() {
        synchronized (mLock) {
            return mBatteryProps.batteryLevel;
        }
    }

    /**
     * Returns whether we currently consider the battery level to be low.
     */
    public boolean getBatteryLevelLow() {
        synchronized (mLock) {
            return mBatteryLevelLow;
        }
    }

    public boolean shouldSendBatteryLowLocked() {
    private boolean shouldSendBatteryLowLocked() {
        final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
        final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;

@@ -277,15 +254,6 @@ public final class BatteryService extends Binder {
                && (oldPlugged || mLastBatteryLevel > mLowBatteryWarningLevel);
    }

    /**
     * Returns a non-zero value if an  unsupported charger is attached.
     */
    public int getInvalidCharger() {
        synchronized (mLock) {
            return mInvalidCharger;
        }
    }

    private void shutdownIfNoPowerLocked() {
        // shut down gracefully if our battery is critically low and we are not powered.
        // wait until the system has booted before attempting to display the shutdown dialog.
@@ -640,17 +608,7 @@ public final class BatteryService extends Binder {
        }
    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
                != PackageManager.PERMISSION_GRANTED) {

            pw.println("Permission Denial: can't dump Battery service from from pid="
                    + Binder.getCallingPid()
                    + ", uid=" + Binder.getCallingUid());
            return;
        }

    private void dumpInternal(PrintWriter pw, String[] args) {
        synchronized (mLock) {
            if (args == null || args.length == 0 || "-a".equals(args[0])) {
                pw.println("Current Battery Service state:");
@@ -801,4 +759,57 @@ public final class BatteryService extends Binder {
            }
       }
    }

    private final class BinderService extends Binder {
        @Override
        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
            if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
                    != PackageManager.PERMISSION_GRANTED) {

                pw.println("Permission Denial: can't dump Battery service from from pid="
                        + Binder.getCallingPid()
                        + ", uid=" + Binder.getCallingUid());
                return;
            }

            dumpInternal(pw, args);
        }
    }

    private final class LocalService extends BatteryManagerInternal {
        @Override
        public boolean isPowered(int plugTypeSet) {
            synchronized (mLock) {
                return isPoweredLocked(plugTypeSet);
            }
        }

        @Override
        public int getPlugType() {
            synchronized (mLock) {
                return mPlugType;
            }
        }

        @Override
        public int getBatteryLevel() {
            synchronized (mLock) {
                return mBatteryProps.batteryLevel;
            }
        }

        @Override
        public boolean getBatteryLevelLow() {
            synchronized (mLock) {
                return mBatteryLevelLow;
            }
        }

        @Override
        public int getInvalidCharger() {
            synchronized (mLock) {
                return mInvalidCharger;
            }
        }
    }
}
+6 −13
Original line number Diff line number Diff line
@@ -19,19 +19,16 @@ package com.android.server.job.controllers;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.BatteryProperty;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.BatteryManagerInternal;
import android.os.SystemClock;
import android.util.Slog;

import com.android.internal.annotations.VisibleForTesting;
import com.android.server.BatteryService;
import com.android.server.LocalServices;
import com.android.server.job.JobSchedulerService;
import com.android.server.job.StateChangedListener;

@@ -158,14 +155,10 @@ public class BatteryController extends StateController {
            mContext.registerReceiver(this, filter);

            // Initialise tracker state.
            BatteryService batteryService = (BatteryService) ServiceManager.getService("battery");
            if (batteryService != null) {
                mBatteryHealthy = !batteryService.getBatteryLevelLow();
                mCharging = batteryService.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
            } else {
                // Unavailable for some reason, we default to false and let ACTION_BATTERY_[OK,LOW]
                // sort it out.
            }
            BatteryManagerInternal batteryManagerInternal =
                    LocalServices.getService(BatteryManagerInternal.class);
            mBatteryHealthy = !batteryManagerInternal.getBatteryLevelLow();
            mCharging = batteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
        }

        boolean isOnStablePower() {
+9 −9
Original line number Diff line number Diff line
@@ -19,7 +19,6 @@ package com.android.server.power;
import com.android.internal.app.IAppOpsService;
import com.android.internal.app.IBatteryStats;
import com.android.internal.os.BackgroundThread;
import com.android.server.BatteryService;
import com.android.server.EventLogTags;
import com.android.server.LocalServices;
import com.android.server.ServiceThread;
@@ -43,6 +42,7 @@ import android.hardware.display.DisplayManagerInternal;
import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.BatteryManagerInternal;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
@@ -168,7 +168,7 @@ public final class PowerManagerService extends com.android.server.SystemService
    private final PowerManagerHandler mHandler;

    private LightsManager mLightsManager;
    private BatteryService mBatteryService;
    private BatteryManagerInternal mBatteryManagerInternal;
    private DisplayManagerInternal mDisplayManagerInternal;
    private IBatteryStats mBatteryStats;
    private IAppOpsService mAppOps;
@@ -463,14 +463,14 @@ public final class PowerManagerService extends com.android.server.SystemService
        Watchdog.getInstance().addThread(mHandler);
    }

    public void systemReady(BatteryService batteryService, IAppOpsService appOps) {
    public void systemReady(IAppOpsService appOps) {
        synchronized (mLock) {
            mSystemReady = true;
            mBatteryService = batteryService;
            mAppOps = appOps;
            mDreamManager = getLocalService(DreamManagerInternal.class);
            mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
            mPolicy = getLocalService(WindowManagerPolicy.class);
            mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);

            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
@@ -1158,10 +1158,10 @@ public final class PowerManagerService extends com.android.server.SystemService
            final boolean wasPowered = mIsPowered;
            final int oldPlugType = mPlugType;
            final boolean oldLevelLow = mBatteryLevelLow;
            mIsPowered = mBatteryService.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
            mPlugType = mBatteryService.getPlugType();
            mBatteryLevel = mBatteryService.getBatteryLevel();
            mBatteryLevelLow = mBatteryService.getBatteryLevelLow();
            mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
            mPlugType = mBatteryManagerInternal.getPlugType();
            mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
            mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();

            if (DEBUG_SPEW) {
                Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
@@ -1244,7 +1244,7 @@ public final class PowerManagerService extends com.android.server.SystemService
            final boolean wasStayOn = mStayOn;
            if (mStayOnWhilePluggedInSetting != 0
                    && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
                mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting);
                mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
            } else {
                mStayOn = false;
            }
+3 −13
Original line number Diff line number Diff line
@@ -150,7 +150,6 @@ public final class SystemServer {
    private DisplayManagerService mDisplayManagerService;
    private PackageManagerService mPackageManagerService;
    private PackageManager mPackageManager;
    private BatteryService mBatteryService;
    private ContentResolver mContentResolver;

    private boolean mOnlyCore;
@@ -362,11 +361,8 @@ public final class SystemServer {
        // Manages LEDs and display backlight.
        mSystemServiceManager.startService(LightsService.class);

        // Tracks the battery level.
        Slog.i(TAG, "Battery Service");
        mBatteryService = new BatteryService(mSystemContext,
                LocalServices.getService(LightsManager.class));
        ServiceManager.addService("battery", mBatteryService);
        // Tracks the battery level.  Requires LightService.
        mSystemServiceManager.startService(BatteryService.class);
    }

    /**
@@ -998,8 +994,7 @@ public final class SystemServer {

        try {
            // TODO: use boot phase
            mPowerManagerService.systemReady(mBatteryService,
                    mActivityManagerService.getAppOpsService());
            mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
        } catch (Throwable e) {
            reportWtf("making Power Manager Service ready", e);
        }
@@ -1066,11 +1061,6 @@ public final class SystemServer {
                } catch (Throwable e) {
                    reportWtf("making Mount Service ready", e);
                }
                try {
                    mBatteryService.systemReady();
                } catch (Throwable e) {
                    reportWtf("making Battery Service ready", e);
                }
                try {
                    if (networkScoreF != null) networkScoreF.systemReady();
                } catch (Throwable e) {