热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

Android如何实现亮度自动调节

这篇文章主要介绍了Android如何实现亮度自动调节,帮助大家更好的理解和学习使用Android开发,感兴趣的朋友可以了解下

下拉状态栏有个亮度的进度条,如果开启了亮度自动调节开关,会随着周围光线变化,这个进度条也会随着变化,接下来就是看看这个功能是如何实现的。

源码版本

基于 Android 9.0 分析。

BrightnessDialog,位于:
frameworks/base/packages/SystemUI/src/com/android/systemui/settings/BrightnessDialog.java

ToggleSliderView,位于:
frameworks/base/packages/SystemUI/src/com/android/systemui/settings/ToggleSliderView.java

DisplayPowerController,位于:
frameworks/base/services/core/java/com/android/server/display/DisplayPowerController.java

AutomaticBrightnessController,位于:
frameworks/base/services/core/java/com/android/server/display/AutomaticBrightnessController.java

BrightnessMappingStrategy,

概述

状态栏里亮度页面是 BrightnessDialog,其中进度条设置是 ToggleSliderView,亮度自动调节主要是 DisplayPowerController 和 AutomaticBrightnessController 两个类,当亮度发生变化时,如果关联到 ToggleSliderView,用的是 ContentObserver,Uri 为 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ。

源码梳理

1、BrightnessDialog#onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //省略部分代码
  mBrightnessCOntroller= new BrightnessController(this, icon, slider);
}

2、这里进行了 BrightnessController 初始化,来看下:

public BrightnessController(Context context, ImageView icon, ToggleSlider control) {
  //省略部分代码
  mBrightnessObserver = new BrightnessObserver(mHandler);
  //省略部分代码
}

又进行了 BrightnessObserver 初始化:

/** ContentObserver to watch brightness **/
private class BrightnessObserver extends ContentObserver {
  //省略部分代码
  private final Uri BRIGHTNESS_FOR_VR_URI =
      Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_FOR_VR);
  //Add By WuXiaolong for AutomaticBrightness
  private final Uri BRIGHTNESS_ADJ_URI =
      Settings.System.getUriFor(Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ);
  public BrightnessObserver(Handler handler) {
    super(handler);
  }
  @Override
  public void onChange(boolean selfChange) {
    onChange(selfChange, null);
  }
  @Override
  public void onChange(boolean selfChange, Uri uri) {
    if (selfChange) return;
    if (BRIGHTNESS_MODE_URI.equals(uri)) {
      mBackgroundHandler.post(mUpdateModeRunnable);
      mBackgroundHandler.post(mUpdateSliderRunnable);
    } 
    //省略部分代码
    //Add By WuXiaolong for AutomaticBrightness
    else if (BRIGHTNESS_ADJ_URI.equals(uri) && mAutomatic) {
      mBackgroundHandler.post(mUpdateSliderRunnable);
    } else {
      mBackgroundHandler.post(mUpdateModeRunnable);
      mBackgroundHandler.post(mUpdateSliderRunnable);
    }
    for (BrightnessStateChangeCallback cb : mChangeCallbacks) {
      cb.onBrightnessLevelChanged();
    }
  }
  public void startObserving() {
    final ContentResolver cr = mContext.getContentResolver();
    cr.unregisterContentObserver(this);
    //省略部分代码
    cr.registerContentObserver(
        BRIGHTNESS_FOR_VR_URI,
        false, this, UserHandle.USER_ALL);
    //Add By WuXiaolong for AutomaticBrightness
    cr.registerContentObserver(
        BRIGHTNESS_ADJ_URI,
        false, this, UserHandle.USER_ALL);
  }
  public void stopObserving() {
    final ContentResolver cr = mContext.getContentResolver();
    cr.unregisterContentObserver(this);
  }
}

其实我目前下载的源码,这块功能是不全的,我已经加上了,哪里进行 BrightnessObserver 的 ContentObserver 注册呢?

3、回到 BrightnessDialog#onStart:

@Override
protected void onStart() {
  super.onStart();
  mBrightnessController.registerCallbacks();
  MetricsLogger.visible(this, MetricsEvent.BRIGHTNESS_DIALOG);
}

4、调用mBrightnessController.registerCallbacks();最终走到 mStartListeningRunnable:

private final Runnable mStartListeningRunnable = new Runnable() {
  @Override
  public void run() {
    //BrightnessObserver 注册
    mBrightnessObserver.startObserving();
    mUserTracker.startTracking();
    // Update the slider and mode before attaching the listener so we don't
    // receive the onChanged notifications for the initial values.
    mUpdateModeRunnable.run();
    mUpdateSliderRunnable.run();
    mHandler.sendEmptyMessage(MSG_ATTACH_LISTENER);
  }
};

当亮度有变化时,会走 BrightnessObserver#onChange,最终走到:

private final Handler mHandler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
    mExternalChange = true;
    try {
      switch (msg.what) {
        //省略部分代码
        case MSG_UPDATE_SLIDER:
          updateSlider(msg.arg1, msg.arg2 != 0);
          break;
        //省略部分代码
        default:
          super.handleMessage(msg);
      }
    } finally {
      mExternalChange = false;
    }
  }
};

走 updateSlider方法,到 :

private void animateSliderTo(int target) {
  if (!mControlValueInitialized) {
    // Don't animate the first value since it's default state isn't mea
    mControl.setValue(target);
    mCOntrolValueInitialized= true;
  }
  //省略部分代码
}

5、跳到 ToggleSliderView#setValue:

@Override
public void setValue(int value) {
  //这里正是修改进度条
  mSlider.setProgress(value);
  if (mMirror != null) {
    mMirror.setValue(value);
  }
}

接下来就是看看亮度自动调节主要的两个类 DisplayPowerController 和 AutomaticBrightnessController。DisplayPowerController 属于 Display 模块,其控制设备屏幕亮灭、背光、与Power关系密切,这里主要看下屏幕亮度的控制这方面的逻辑。

6、首先,在 DisplayManagerService 中初始化 DisplayPowerController,如下:

private final class LocalService extends DisplayManagerInternal {
  @Override
  public void initPowerManagement(final DisplayPowerCallbacks callbacks, Handler handler,
      SensorManager sensorManager) {
    synchronized (mSyncRoot) {
      //省略部分代码
      mDisplayPowerCOntroller= new DisplayPowerController(
          mContext, callbacks, handler, sensorManager, blanker);
    }
    mHandler.sendEmptyMessage(MSG_LOAD_BRIGHTNESS_CONFIGURATION);
  }

7、接着看下 DisplayPowerController 构造方法,如下:

public DisplayPowerController(Context context,
    DisplayPowerCallbacks callbacks, Handler handler,
    SensorManager sensorManager, DisplayBlanker blanker) {
  //省略部分代码
  mUseSoftwareAutoBrightnessCOnfig= resources.getBoolean(
      com.android.internal.R.bool.config_automatic_brightness_available);
  //省略部分代码
  if (mUseSoftwareAutoBrightnessConfig) {
    //省略部分代码
    mBrightnessMapper = BrightnessMappingStrategy.create(resources);
    if (mBrightnessMapper != null) {
      mAutomaticBrightnessCOntroller= new AutomaticBrightnessController(this,
          handler.getLooper(), sensorManager, mBrightnessMapper,
          lightSensorWarmUpTimeConfig, mScreenBrightnessRangeMinimum,
          mScreenBrightnessRangeMaximum, dozeScaleFactor, lightSensorRate,
          initialLightSensorRate, brighteningLightDebounce, darkeningLightDebounce,
          autoBrightnessResetAmbientLuxAfterWarmUp, hysteresisLevels);
    } else {
      mUseSoftwareAutoBrightnessCOnfig= false;
    }
  }
  //省略部分代码
  mAutoBrightnessAdjustment = getAutoBrightnessAdjustmentSetting();
  mTemporaryAutoBrightnessAdjustment = Float.NaN;
  //省略部分代码
}

由于亮屏之后屏幕自动亮度才会生效,所以在亮屏的时候,流程会走到 DisplayPowerController 中的核心函数 updatePowerState():

private void updatePowerState() {
  // Update the power state request.
  //省略部分代码
  
  final boolean autoBrightnessAdjustmentChanged = updateAutoBrightnessAdjustment();
  if (autoBrightnessAdjustmentChanged) {
    mTemporaryAutoBrightnessAdjustment = Float.NaN;
  }
  // Use the autobrightness adjustment override if set.
  final float autoBrightnessAdjustment;
  if (!Float.isNaN(mTemporaryAutoBrightnessAdjustment)) {
    autoBrightnessAdjustment = mTemporaryAutoBrightnessAdjustment;
    mAppliedTemporaryAutoBrightnessAdjustment = true;
  } else {
    autoBrightnessAdjustment = mAutoBrightnessAdjustment;
    mAppliedTemporaryAutoBrightnessAdjustment = false;
  }
  
  boolean hadUserBrightnessPoint = false;
  // Configure auto-brightness.
  if (mAutomaticBrightnessController != null) {
    hadUserBrightnessPoint = mAutomaticBrightnessController.hasUserDataPoints();
    mAutomaticBrightnessController.configure(autoBrightnessEnabled,
        mBrightnessConfiguration,
        mLastUserSetScreenBrightness / (float) PowerManager.BRIGHTNESS_ON,
        userSetBrightnessChanged, autoBrightnessAdjustment,
        autoBrightnessAdjustmentChanged, mPowerRequest.policy);
  }
  
  // Apply auto-brightness.
  boolean slowChange = false;
  if (brightness <0) {
    float newAutoBrightnessAdjustment = autoBrightnessAdjustment;
    if (autoBrightnessEnabled) {
      brightness = mAutomaticBrightnessController.getAutomaticScreenBrightness();
      newAutoBrightnessAdjustment =
          mAutomaticBrightnessController.getAutomaticScreenBrightnessAdjustment();
    }
    if (brightness >= 0) {
      // Use current auto-brightness value and slowly adjust to changes.
      brightness = clampScreenBrightness(brightness);
      if (mAppliedAutoBrightness && !autoBrightnessAdjustmentChanged) {
        slowChange = true; // slowly adapt to auto-brightness
      }
      // Tell the rest of the system about the new brightness. Note that we do this
      // before applying the low power or dim transformations so that the slider
      // accurately represents the full possible range, even if they range changes what
      // it means in absolute terms.
      putScreenBrightnessSetting(brightness);
      mAppliedAutoBrightness = true;
    } else {
      mAppliedAutoBrightness = false;
    }
    if (autoBrightnessAdjustment != newAutoBrightnessAdjustment) {
      // If the autobrightness controller has decided to change the adjustment value
      // used, make sure that's reflected in settings.
      putAutoBrightnessAdjustmentSetting(newAutoBrightnessAdjustment);
    }
  } else {
    mAppliedAutoBrightness = false;
  }
  //省略部分代码
}

接下来分别看看 autoBrightnessAdjustment 和 newAutoBrightnessAdjustment 怎么来的?

autoBrightnessAdjustment 是来自 mTemporaryAutoBrightnessAdjustment 或 mAutoBrightnessAdjustment 赋值,mAutoBrightnessAdjustment 在第 7 步mAutoBrightnessAdjustment = getAutoBrightnessAdjustmentSetting();有初始化,看下 getAutoBrightnessAdjustmentSetting():

private float getAutoBrightnessAdjustmentSetting() {
  final float adj = Settings.System.getFloatForUser(mContext.getContentResolver(),
      Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f, UserHandle.USER_CURRENT);
  return Float.isNaN(adj) &#63; 0.0f : clampAutoBrightnessAdjustment(adj);
}

继续看下 clampAutoBrightnessAdjustment:

private static float clampAutoBrightnessAdjustment(float value) {
  return MathUtils.constrain(value, -1.0f, 1.0f);
}

这里注意下 MathUtils.constrain() 表示百分比缩放函数,比如 MathUtils.constrain(0.5, 0, 255) 表示 (255-0)*0.5。

这样了解了 autoBrightnessAdjustment,接下来看 newAutoBrightnessAdjustment。

8、回到 DisplayPowerController#updatePowerState(),

看到 newAutoBrightnessAdjustment 调用了 AutomaticBrightnessController.getAutomaticScreenBrightnessAdjustment(),最终是到了 BrightnessMapper#getAutoBrightnessAdjustment() 其中 mAutoBrightnessAdjustment 变量,赋值是在 BrightnessMapper#setAutoBrightnessAdjustment:

@Override
public boolean setAutoBrightnessAdjustment(float adjustment) {
  adjustment = MathUtils.constrain(adjustment, -1, 1);
  if (adjustment == mAutoBrightnessAdjustment) {
    return false;
  }
  if (DEBUG) {
    Slog.d(TAG, "setAutoBrightnessAdjustment: " + mAutoBrightnessAdjustment + " => " +
        adjustment);
    PLOG.start("auto-brightness adjustment");
  }
  mAutoBrightnessAdjustment = adjustment;
  computeSpline();
  return true;
}

9、BrightnessMapper#setAutoBrightnessAdjustment

这个方法调用又回到了 AutomaticBrightnessController#setAutoBrightnessAdjustment:

private boolean setAutoBrightnessAdjustment(float adjustment) {
  return mBrightnessMapper.setAutoBrightnessAdjustment(adjustment);
}

AutomaticBrightnessController#setAutoBrightnessAdjustment调用是来到 AutomaticBrightnessController#configure()方法:

public void configure(boolean enable, @Nullable BrightnessConfiguration configuration,
    float brightness, boolean userChangedBrightness, float adjustment,
    boolean userChangedAutoBrightnessAdjustment, int displayPolicy) {
  // While dozing, the application processor may be suspended which will prevent us from
  // receiving new information from the light sensor. On some devices, we may be able to
  // switch to a wake-up light sensor instead but for now we will simply disable the sensor
  // and hold onto the last computed screen auto brightness. We save the dozing flag for
  // debugging purposes.
  boolean dozing = (displayPolicy == DisplayPowerRequest.POLICY_DOZE);
  boolean changed = setBrightnessConfiguration(configuration);
  changed |= setDisplayPolicy(displayPolicy);
  if (userChangedAutoBrightnessAdjustment) {
    changed |= setAutoBrightnessAdjustment(adjustment);
  }
  if (userChangedBrightness && enable) {
    // Update the brightness curve with the new user control point. It's critical this
    // happens after we update the autobrightness adjustment since it may reset it.
    changed |= setScreenBrightnessByUser(brightness);
  }
  final boolean userInitiatedChange =
      userChangedBrightness || userChangedAutoBrightnessAdjustment;
  if (userInitiatedChange && enable && !dozing) {
    prepareBrightnessAdjustmentSample();
  }
  changed |= setLightSensorEnabled(enable && !dozing);
  if (changed) {
    updateAutoBrightness(false /*sendUpdate*/);
  }
}

AutomaticBrightnessController#configure()调用来到了 DisplayPowerController #updatePowerState()。

这样也知道了 newAutoBrightnessAdjustment,继续 putAutoBrightnessAdjustmentSetting:

private void putAutoBrightnessAdjustmentSetting(float adjustment) {
  mAutoBrightnessAdjustment = adjustment;
  Settings.System.putFloatForUser(mContext.getContentResolver(),
      Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, adjustment, UserHandle.USER_CURRENT);
}

就调到第 4 步 BrightnessObserver#onChange,进度条随之变化,Over!

以上就是Android 如何实现亮度自动调节的详细内容,更多关于Android 亮度自动调节的资料请关注其它相关文章!


推荐阅读
  • 深入理解Lucene搜索机制
    本文旨在帮助读者全面掌握Lucene搜索的编写步骤、核心API及其应用。通过详细解析Lucene的基本查询和查询解析器的使用方法,结合架构图和代码示例,带领读者深入了解Lucene搜索的工作流程。 ... [详细]
  • 本文介绍如何使用 Android 的 Canvas 和 View 组件创建一个简单的绘图板应用程序,支持触摸绘画和保存图片功能。 ... [详细]
  • 本文详细介绍了划分树这一数据结构,重点探讨了其在子树和中值计算中的应用及优化方法。 ... [详细]
  • Android Studio 安装与配置指南
    本教程详细介绍了如何下载并安装 Android Studio,包括设置 SDK 路径和优化启动性能的方法。通过这些步骤,您可以顺利地开始开发 Android 应用。 ... [详细]
  • Appium + Java 自动化测试中处理页面空白区域点击问题
    在进行移动应用自动化测试时,有时会遇到某些页面没有返回按钮,只能通过点击空白区域返回的情况。本文将探讨如何在Appium + Java环境中有效解决此类问题,并提供详细的解决方案。 ... [详细]
  • 如何清除Chrome浏览器地址栏的特定历史记录
    在使用Chrome浏览器时,你可能会发现地址栏保存了大量浏览记录。有时你可能希望删除某些特定的历史记录而不影响其他数据。本文将详细介绍如何单独删除地址栏中的特定记录以及批量清除所有历史记录的方法。 ... [详细]
  • 利用Selenium与ChromeDriver实现豆瓣网页全屏截图
    本文介绍了一种使用Selenium和ChromeDriver结合Python代码,轻松实现对豆瓣网站进行完整页面截图的方法。该方法不仅简单易行,而且解决了新版Selenium不再支持PhantomJS的问题。 ... [详细]
  • 嵌入式开发环境搭建与文件传输指南
    本文详细介绍了如何为嵌入式应用开发搭建必要的软硬件环境,并提供了通过串口和网线两种方式将文件传输到开发板的具体步骤。适合Linux开发初学者参考。 ... [详细]
  • 解决TensorFlow CPU版本安装中的依赖问题
    本文记录了在安装CPU版本的TensorFlow过程中遇到的依赖问题及解决方案,特别是numpy版本不匹配和动态链接库(DLL)错误。通过详细的步骤说明和专业建议,帮助读者顺利安装并使用TensorFlow。 ... [详细]
  • 探索新一代API文档工具,告别Swagger的繁琐
    对于后端开发者而言,编写和维护API文档既繁琐又不可或缺。本文将介绍一款全新的API文档工具,帮助团队更高效地协作,简化API文档生成流程。 ... [详细]
  • 本文详细探讨了Android Activity中View的绘制流程和动画机制,包括Activity的生命周期、View的测量、布局和绘制过程以及动画对View的影响。通过实验验证,澄清了一些常见的误解,并提供了代码示例和执行结果。 ... [详细]
  • 本文探讨了在构建应用程序时,如何对不同类型的数据进行结构化设计。主要分为三类:全局配置、用户个人设置和用户关系链。每种类型的数据都有其独特的用途和应用场景,合理规划这些数据结构有助于提升用户体验和系统的可维护性。 ... [详细]
  • 在 Android 开发中,通过 Intent 启动 Activity 或 Service 时,可以使用 putExtra 方法传递数据。接收方可以通过 getIntent().getExtras() 获取这些数据。本文将介绍如何使用 RoboGuice 框架简化这一过程,特别是 @InjectExtra 注解的使用。 ... [详细]
  • Linux中的yum安装软件
    yum俗称大黄狗作用:解决安装软件包的依赖关系当安装依赖关系的软件包时,会将依赖的软件包一起安装。本地yum:需要yum源,光驱挂载。yum源:(刚开始查看yum源中的内容就是上图 ... [详细]
  • 鼠标悬停出现提示信息怎么做
    概述–提示:指启示,提起注意或给予提醒和解释。在excel中会经常用到给某个格子增加提醒信息,比如金额提示输入数值或最大长度值等等。设置方式也有多种,简单的,仅为单元格插入批注就可 ... [详细]
author-avatar
筱美嘚
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有