android 状态栏电量百分比控制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32143319/article/details/70758982

原生google代码没有这个选项 要长按下拉框的设置小图标 打开界面调谐器 才能显示百分比控制,但是也不美观,下面就添加这个功能,直接上修改方法,锁屏界面同步 请看android锁屏界面电量百分比显示与主桌面同步
路径frameworks\base\core\java\android\provider\Settings.java
在这里加入静态变量

// add for battery
         /**
         * turn on/off the battery percentage show in status bar
         * @hide
         */
        public static final String BATTERY_PERCENTAGE = "battery_percentage";
// add end

路径frameworks\base\packages\SettingsProvider\src\com\android\providers\settings\DatabaseHelper.java

 private void loadSecureSettings(SQLiteDatabase db) {
        SQLiteStatement stmt = null;
            ...........
            ...........
//add for battery
            loadSetting(stmt, Settings.Secure.BATTERY_PERCENTAGE,"true");
            ..........
            }

\frameworks\base\packages\SystemUI\res\layout\status_bar.xml加入布局

 <TextView android:id="@+id/battery_level"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginStart="@dimen/header_battery_margin_keyguard"
            android:paddingEnd="@dimen/battery_level_padding_end"
            android:textColor="#ffffff"  
            android:textSize="@dimen/battery_level_text_size"
            android:importantForAccessibility="noHideDescendants"/>

frameworks\base\packages\SystemUI\src\com\android\systemui\statusbar\phone\PhoneStatusBar.java加载布局

    BrightnessMirrorController mBrightnessMirrorController;
    AccessibilityController mAccessibilityController;
    /// M: Add extra tiles @{
    private TextView mBatteryLevel;//add
    //add HotKnot in quicksetting
    HotKnotControllerImpl mHotKnotController;
    //add AudioProfile in quicksetting
protected PhoneStatusBarView makeStatusBarView() {
        ........
           // Other icons
        mLocationController = new LocationControllerImpl(mContext,
        mHandlerThread.getLooper()); // will post a notification
        mBatteryController = new BatteryController(mContext);
        mBatteryController.addLabelView((TextView)mStatusBarWindow.
         findViewById(R.id.battery_level));//add for battery
        mBatteryController.addStateChangedCallback(new BatteryStateChangeCallback() {
            @Override
            public void onPowerSaveChanged() {
                mHandler.post(mCheckBarModes);
                if (mDozeServiceHost != null) {

                }
            }
}

packages\apps\Settings\src\com\mediatek\settings\fuelgauge\PowerUsageExts.java这里加控制开关

//add
import android.os.UserHandle;
import android.content.Intent;
import android.content.IntentFilter;
//add
........
........
public class PowerUsageExts {

 .........
// add for battery
    private static final String KEY_BATTERY_PERCENTAGE = "battery_percentage";
    private static final String ACTION_BATTERY_PERCENTAGE_SWITCH =        "mediatek.intent.action.BATTERY_PERCENTAGE_SWITCH";
     private SwitchPreference mBatterrPercentPrf;
// add end
.......
....... 
public void initPowerUsageExtItems() {
            ..........
            //add for battery
            mBatterrPercentPrf = new SwitchPreference(mContext);
            mBatterrPercentPrf.setKey(KEY_BATTERY_PERCENTAGE);
            mBatterrPercentPrf.setTitle(R.string.battery_percent);
            mBatterrPercentPrf.setOrder(PREFERENCE_ORDER_FIRST);
            mBatterrPercentPrf.setChecked(true);
            mPowerUsageScreen.addPreference(mBatterrPercentPrf);
            //add end

   }
    public boolean onPowerUsageExtItemsClick(PreferenceScreen preferenceScreen,
            Preference preference) {
// modify by for battery
if (preference instanceof SwitchPreference) {

    SwitchPreference pref = (SwitchPreference) preference;
    if(KEY_BACKGROUND_POWER_SAVING.equals(preference.getKey())){
        int bgState = pref.isChecked() ? 1 : 0;
                Log.d(TAG, "background power saving state: " + bgState);
                Settings.System.putInt(mContext.getContentResolver(),
                        Settings.System.BG_POWER_SAVING_ENABLE, bgState);
                if (mBgPowerSavingPrf != null) {
                    mBgPowerSavingPrf.setChecked(pref.isChecked());
                }
    }
    else if(KEY_BATTERY_PERCENTAGE.equals(preference.getKey())){


            int state = pref.isChecked() ? 1 : 0;
            Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.BATTERY_PERCENTAGE, state);

                Intent intent = new Intent(ACTION_BATTERY_PERCENTAGE_SWITCH);
                intent.putExtra("state", state);
                // { @: ALPS01292477
                if (mBatterrPercentPrf != null) {
                    mBatterrPercentPrf.setChecked(pref.isChecked());
                } // @ }
                // @ CR: ALPS00462531 for multi user
                mContext.sendBroadcastAsUser(intent, UserHandle.ALL);

        }
        return true;



} 
//modify by for battery end
        return false;
    }
}

接下来就是接收了
frameworks\base\packages\SystemUI\src\com\android\systemui\statusbar\policy\BatteryController.java

// add by  for battery
import android.widget.TextView;
import android.view.View;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException; 
import android.provider.Settings;

public class BatteryController extends BroadcastReceiver {
    private static final String TAG = "BatteryController";
    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);

    private final ArrayList<BatteryStateChangeCallback> mChangeCallbacks = new ArrayList<>();
    private final PowerManager mPowerManager;

    private int mLevel;
    private boolean mPluggedIn;
    private boolean mCharging;
    private boolean mCharged;
    private boolean mPowerSave;
    // add by for battery
    private TextView view;
    private static final String ACTION_BATTERY_PERCENTAGE_SWITCH = "mediatek.intent.action.BATTERY_PERCENTAGE_SWITCH";
    private boolean mShouldShowBatteryPercentage ;
    private String mBatteryPercentage = "100%";
    private Context otherContext = null;
    private Context myContext = null;
    private String  value;
    // add end
    public BatteryController(Context context) {
// add by for battery
        myContext = context;

         mShouldShowBatteryPercentage = (Settings.Secure.getInt(context
                .getContentResolver(), Settings.Secure.BATTERY_PERCENTAGE, 1) != 0);

// add by for battery end

        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING);
        filter.addAction(ACTION_BATTERY_PERCENTAGE_SWITCH);// add by wsw for battery
        context.registerReceiver(this, filter);

        updatePowerSave();
    }

   // add by for battery
    public void addLabelView(TextView v) {
       view = v;
    }
    private void refreshBatteryPercentage() {

     if (mShouldShowBatteryPercentage) {
                    view.setText(mBatteryPercentage);
                    view.setVisibility(View.VISIBLE);
                } else {
                    view.setVisibility(View.GONE);
                }

    }

     private  String getBatteryPercentage(Intent batteryChangedIntent) {
        int level = batteryChangedIntent.getIntExtra("level", 0);
        int scale = batteryChangedIntent.getIntExtra("scale", 100);
        return String.valueOf(level * 100 / scale) + "%";
    }
// add by for battery end




    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        pw.println("BatteryController state:");
        pw.print("  mLevel="); pw.println(mLevel);
        pw.print("  mPluggedIn="); pw.println(mPluggedIn);
        pw.print("  mCharging="); pw.println(mCharging);
        pw.print("  mCharged="); pw.println(mCharged);
        pw.print("  mPowerSave="); pw.println(mPowerSave);
    }

    public void addStateChangedCallback(BatteryStateChangeCallback cb) {
        mChangeCallbacks.add(cb);
        cb.onBatteryLevelChanged(mLevel, mPluggedIn, mCharging);
    }

    public void removeStateChangedCallback(BatteryStateChangeCallback cb) {
        mChangeCallbacks.remove(cb);
    }

    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
            mLevel = (int)(100f
                    * intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
                    / intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100));
            mPluggedIn = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;

            final int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
                    BatteryManager.BATTERY_STATUS_UNKNOWN);
            mCharged = status == BatteryManager.BATTERY_STATUS_FULL;
            mCharging = mCharged || status == BatteryManager.BATTERY_STATUS_CHARGING;

            fireBatteryLevelChanged();

         // add by for battery


        mBatteryPercentage = getBatteryPercentage(intent);

        refreshBatteryPercentage();

     // add by for battery end
        } else if (action.equals(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)) {
            updatePowerSave();
        } else if (action.equals(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING)) {
            setPowerSave(intent.getBooleanExtra(PowerManager.EXTRA_POWER_SAVE_MODE, false));
       // add by for battery
        } else if(action.equals(ACTION_BATTERY_PERCENTAGE_SWITCH)){
            mShouldShowBatteryPercentage = (intent.getIntExtra("state",0) == 1);
                     refreshBatteryPercentage();
        }
        // add by for battery end




    }

没有更多推荐了,返回首页