Saturday, July 16, 2011

Changing the Screen Brightness Programatically

There are some discussion on Google group on this matter so i try to see if how this problem can be fixed. This problem could be fixed by using something that is not documented and is not advised to use (Its sort of a hack, i'm not responsible if something went wrong on your android). What this app will do it count to 240, 20 per second starting from 0. Then on each count it will set the brightness of your phone.

Anyway here is the how i did it. Please read the Note at the bottom.

First add <uses-permission android:name="android.permission.HARDWARE_TEST"></uses-permission> to your Manifest file.

          package com.monmonja.firstDemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.IHardwareService;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.widget.TextView;

public class Main extends Activity {
  private TextView txtStatus;
  private RefreshHandler mRedrawHandler = new RefreshHandler();

  class RefreshHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
      Main.this.updateUI();
    }

    public void sleep(long delayMillis) {
      this.removeMessages(0);
      sendMessageDelayed(obtainMessage(0), delayMillis);
    }
  };

  private void updateUI(){
    int currentInt = Integer.parseInt((String) txtStatus.getText()) + 20;
    if(currentInt <= 250){
      mRedrawHandler.sleep(1000);
      setBrightness(currentInt);
      txtStatus.setText(String.valueOf(currentInt));
    }
  }

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    this.txtStatus = (TextView) this.findViewById(R.id.txtStatus);
    updateUI();
  }

  private void setBrightness(int brightness) {
    try {
      IHardwareService hardware = IHardwareService.Stub.asInterface(
ServiceManager.getService("hardware"));
      if (hardware != null) {
        hardware.setScreenBacklight(brightness);
      }
    } catch (RemoteException doe) {
    }
  }
}

No comments:

Post a Comment