android_brightness_resolving

原创 2017年06月27日 15:27:06

浅析Brightness的创建和执行流程:

步凑一 系统中packages\apps\Settings\res\xml\display_settings.xml中有添加preference组件:

        <com.android.settings.BrightnessPreference
                android:title="@string/brightness"
                android:persistent="false"/>
//在自定义BrightnessPreference.java中只发送了一条广播:

public class BrightnessPreference extends Preference {


    public BrightnessPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onClick() {
      //发送了一个显示亮度调节对话框的广播
    Intent intent = new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG); 
    getContext().sendBroadcastAsUser(intent, UserHandle.CURRENT_OR_SELF); }}

步凑二 接收广播并且显示BrightnessDialog菜单的消息是在framework中接收处理的:

public class SettingsUI extends SystemUI {
    private static final String TAG = "SettingsUI";
    private static final boolean DEBUG = false;

    private final Handler mHandler = new Handler();
    private BrightnessDialog mBrightnessDialog;

    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG)) {
                if (DEBUG) Log.d(TAG, "showing brightness dialog");
                if (mBrightnessDialog == null) {
                   //创建BrightnessDialog实例
                    mBrightnessDialog = new BrightnessDialog(mContext);
                    mBrightnessDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            mBrightnessDialog = null;
                        }
                    });
                }

                if (!mBrightnessDialog.isShowing()) {
                //显示brightnessDialog
                    mBrightnessDialog.show();
                }

            } else {
                Log.w(TAG, "unknown intent: " + intent);
            }
        }
    };

    public void start() {
        //监听ACTION_SHOW_BRIGHTNESS_DIALOG的广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG);
        mContext.registerReceiverAsUser(mIntentReceiver, UserHandle.ALL, filter, null, mHandler);
    }

步凑三 创建seekbar布局定义的结构层次是:

       1.BrightnessDialog.java
       2.BrightnessDialog.java中创建了quick_settings_brightness_dialog
       3.quick_settings_brightness_dialog中自定义了控件com.android.systemui.settings.ToggleSlider
       4.ToggleSlider.java中真正创建了seekbar控件。
       如下是:BrightnessDialog.java

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.setType(WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY);
        window.getAttributes().privateFlags |=
                WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
        window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        window.requestFeature(Window.FEATURE_NO_TITLE);

        /*SPRD bug 636829:Don't auto dismiss brightness dialog*/
        window.setGravity(Gravity.CENTER_VERTICAL);
        setContentView(R.layout.quick_settings_brightness_dialog);
        setCanceledOnTouchOutside(true);
    }

       如下是quick_settings_brightness_dialog布局文件:

    <TextView
        android:id="@+id/tab_switch_container_display"
        android:layout_centerVertical="true"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffffffff"
        android:textSize="18px"
        android:text="@string/label_screen_brightness"/>

    <com.android.systemui.settings.ToggleSlider
        android:id="@+id/brightness_slider"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"
        systemui:text="@string/status_bar_settings_auto_brightness_label" />

        如下是:com.android.systemui.settings.ToggleSlider文件  

    public ToggleSlider(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        View.inflate(context, R.layout.status_bar_toggle_slider, this);
        final Resources res = context.getResources();
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ToggleSlider,
                defStyle, 0);

        mToggle = (CompoundButton)findViewById(R.id.toggle);
        
        /* SPRD:Modify Bug 333649, remove brightness auto set @{ */
        if (fileIsExists()) {
            mToggle.setOnCheckedChangeListener(this);
            mToggle.setBackgroundDrawable(res.getDrawable(R.drawable.status_bar_toggle_button));
        }
        /* @} */

        mSlider = (SeekBar)findViewById(R.id.slider);
        mSlider.setOnSeekBarChangeListener(this);

        mLabel = (TextView)findViewById(R.id.label);
        mLabel.setVisibility(GONE);
        /* SPRD:Modify Bug 333649, remove brightness auto set @{ */
        /* SPRD: Bug 583693 PikeL Feature {@ */
        //if (fileIsExists()) {
            //mLabel.setText(a.getString(R.styleable.ToggleSlider_text));
        //}
        /* @} */

        a.recycle();
    }
    如下是:真正创建了seekbar控件

    <com.android.systemui.settings.ToggleSeekBar
        android:id="@+id/slider"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/toggle"
        android:layout_centerVertical="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:paddingStart="20dp"
        android:paddingEnd="20dp"
        android:paddingTop="12dp"
        android:paddingBottom="12dp"
        //设置拖动进度条上的拇指图标
        android:thumb="@drawable/ic_brightness_thumb_customized"
       

步凑四 对亮度的真正调节效果是使用了BrightnessDialog.java中的BrightnessController

    protected void onStart() {
        super.onStart();
        mBrightnessController = new BrightnessController(getContext(),
                (ImageView) findViewById(R.id.brightness_icon),
                (ToggleSlider) findViewById(R.id.brightness_slider));
        dismissBrightnessDialog(mBrightnessDialogLongTimeout);
        mBrightnessController.addStateChangedCallback(this);

对BrightnessController中的浅析:
在上面onStart中创建了BrightnessDialog对象时构造函数中做了如下操作:

   public BrightnessController(Context context, ImageView icon, ToggleSlider control) {
        mContext = context;
        mIcon = icon;
        mControl = control;
        /* SPRD: add to optimize oom for bug 295792 @{ */
       //接收SCREEN_BRIGHTNESS_MESSAGE_ID发送过来的消息处理:(保存亮度值的方式二种用到的方法,在下面代码中)
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                if (msg.what == SCREEN_BRIGHTNESS_MESSAGE_ID) {
                    //保存当前的亮度值至Settings.system系统中
                    Settings.System.putIntForUser(mContext.getContentResolver(),
                            Settings.System.SCREEN_BRIGHTNESS, msg.arg1,
                            UserHandle.USER_CURRENT);
                }
            }
        };
        /* @} */
        mUserTracker = new CurrentUserTracker(mContext) {
            @Override
            public void onUserSwitched(int newUserId) {
                updateMode();
                updateSlider();
            }
        };
       //创建观察者模式监控亮屏的模式和亮度值状态,当发生改变时进行更新
        mBrightnessObserver = new BrightnessObserver(mHandler);
        mBrightnessObserver.startObserving();

       //获取PowerManager对象,从而获得亮度的最大值和最小亮度值     
        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        mMinimumBacklight = pm.getMinimumScreenBrightnessSetting();
        mMaximumBacklight = pm.getMaximumScreenBrightnessSetting();


        mAutomaticAvailable = context.getResources().getBoolean(
                com.android.internal.R.bool.config_automatic_brightness_available);
       //获取IpowerManager对象
        mPower = IPowerManager.Stub.asInterface(ServiceManager.getService("power"));


        // Update the slider and mode before attaching the listener so we don't receive the
        // onChanged notifications for the initial values.
        updateMode();
        updateSlider();


        control.setOnChangedListener(this);
    }

其中ToggleSlider文件中对seekbar控件进行监控事件处理的三个重写的方法:

     //拖动中
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (mListener != null) {
            mListener.onChanged(this, mTracking, mToggle.isChecked(), progress);
        }
    }
    //开始拖动
    public void onStartTrackingTouch(SeekBar seekBar) {
        mTracking = true;
        if (mListener != null) {
            mListener.onChanged(this, mTracking, mToggle.isChecked(), mSlider.getProgress());
        }
        mToggle.setChecked(false);
    }
    //停止拖动
    public void onStopTrackingTouch(SeekBar seekBar) {
        mTracking = false;
        if (mListener != null) {
            mListener.onChanged(this, mTracking, mToggle.isChecked(), mSlider.getProgress());
        }
    }


在BrightnessController.java中实际处理了如下信息:
    public void onChanged(ToggleSlider view, boolean tracking, boolean automatic, int value) {
       //设置亮度的设置模式,mode=0表示为手动,mode=1表示自动调节
        setMode(automatic ? Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
                : Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        updateIcon(automatic);
        if (!automatic) {
            final int val = value + mMinimumBacklight;
            //设置屏幕的亮度
            setBrightness(val);
            // SPRD: fixbug364442 add log for brightness control.
            Log.d(TAG, "onChanged : value =" + value + " , mMinimumBacklight =" +
                    mMinimumBacklight + " , tracking =" + tracking);
            //以下的设置是将屏幕的亮度值保存到settings/system中的两种方式
           //方式一:直接putIntForUser
            if (!tracking) {
                /* SPRD: add to optimize oom for bug 295792 @{
                 * @origin: we move it to handlemessage beicause there are too many runnables
                 * AsyncTask.execute(new Runnable() {
                 * public void run() {
                 *            Settings.System.putIntForUser(mContext.getContentResolver(),
                 *                    Settings.System.SCREEN_BRIGHTNESS, val,
                 *                    UserHandle.USER_CURRENT);
                 *        }
                 *    });
                 */
           //方式二:通过handle  发送一个SCREEN_BRIGHTNESS_MESSAGE_ID消息给到接收方处理保存亮度。
                mHandler.removeMessages(SCREEN_BRIGHTNESS_MESSAGE_ID);
                //发送SCREEN_BRIGHTNESS_MESSAGE_ID消息
                mHandler.obtainMessage(SCREEN_BRIGHTNESS_MESSAGE_ID, val, -1).sendToTarget();
                /* @} */
            }
        }

        for (BrightnessStateChangeCallback cb : mChangeCallbacks) {
            cb.onBrightnessLevelChanged();
        }
    }
附加:设置屏亮度
    private void setBrightness(int brightness) {
        try {
            mPower.setTemporaryScreenBrightnessSettingOverride(brightness);
        } catch (RemoteException ex) {
        }
    }
设置亮屏模式:

    private void setMode(int mode) {
        Settings.System.putIntForUser(mContext.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE, mode,
                mUserTracker.getCurrentUserId());
    }

时间关系,只能仓促的这样结束了,条理不怎么清晰,看不懂莫怪,还有可能误导大家,写这个就是希望有人能指正我的错误,仅供参考吧!








版权声明:本文为博主原创文章,未经博主允许不得转载。

Android 获取和设置屏幕亮度的模式和值

最近有一个需求,是要能够设置Android的屏幕的亮度的模式和值。简单来说,就是把原生设置里面就有的功能再用自己的UI做一遍。 OK,接下来就是查看源码。 首先找到显示的java类,是在setting...

android亮度brightness

最近在做一个App的设置项,亮度调节。真正做时,发现Android亮度调节比预想要复杂一些。其实目前网上已有不少这方面的资料,但有些博文具有一定误导性。在此将这块内容按照自己理解整理一下。 整体上看,...

Android Brightness Changing

这内容挺用的,特别是需要调节亮度的程序,自己收藏起来,呵呵。这段代码不只能改变当前的Activity,也可以改变整个System的亮度 代码: package com.jimmy; import...

我的Android进阶之旅------>自己写个Activity来调节Android系统背光亮度Brightness

今天终于算初步写好了一个调节系统背光亮度Brightness的代码,本来不看Android源代码以为可以直接调用某个Action来启动系统的那个调节Brightness的对话框,但是看了代码后发现系统...

This document in intended to assist with identifying and resolving system panics related to Solaris

This document in intended to assist with identifying and resolving system panics related to Solaris ...

FAQ about Detecting and Resolving Locking Conflicts(oracle deadlock 学习资料-02)

从别去转来的一份文档。

MyBtais错误:org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.a

Cause: java.lang.ClassNotFoundException: Cannot find class: BaseResultMap at org.springframework...

关于专利APPROACH FOR RESOLVING OCCLUSIONS, SPLITS AND MERGES IN VIDEO IMAGES

这是一篇关于视频处理中的遮挡处理一个专利,是因为看到blobdetect程序中提到这个才看的。因为这个专利中有图,写语言的也很简单,很好理解,应该说是和常规思维很相似,但是不知道怎么觉得没学到什么东西...

Resolving Ext3 Error: No journal on filesystem

Ext3 is a journaled file system and maintains a journal file to prevent instances of metadata corrup...

Resolving a 'sticky tag is not a branch' error

from: http://drupal.org/node/57516 Edited by jhodgdon, aclight, dww, kbahey.  Last updated Ma...
  • flex4
  • flex4
  • 2012年07月11日 01:14
  • 442
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:android_brightness_resolving
举报原因:
原因补充:

(最多只允许输入30个字)