在android 开发中有的时候我们会用到contentobserver,contentobserver被称为内容观察者,它不仅能监听到数据库中数据的变化,也能对系统中的某些数据进行监听,像屏幕的亮度,系统的声音等.本次主要说的对系统的亮度进行监听.
先写一个类extends contentobserver ,重写onchange(boolean),在onchange中进行监听,当亮度变化时候进行处理,
在这里当亮度变化用一handler来显示Toast.
public class BrightnessValue extends ContentObserver{ private Handler handler; public BrightnessValue(Handler handler) { super(handler); // TODO Auto-generated constructor stub this.handler = handler; } @Override public void onChange(boolean selfChange) { // TODO Auto-generated method stub super.onChange(selfChange); try { int BrightnessValue = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); Log.i(">>>>>>>>>>>>>>>Hook brightness value : ",String.valueOf(BrightnessValue)); handler.sendEmptyMessage(1); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); Toast.makeText(this, "The brightness value has changed", 1000).show(); } };
當然,只是做一個這樣的監聽是不行的,還需要對它進行註冊,只有註冊才能進行監聽.
public void registerOberver(){ Uri uri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS); getContentResolver().registerContentObserver(uri, false, BrightnessObserver); }
最後,在onCreat方法中加兩條就好了.
BrightnessObserver = new BrightnessValue(mHandler); registerOberver();