2011년 5월 18일 수요일

Android - Battery 잔량 표시

private TextView contentTxt;

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        
        contentTxt = new TextView(this);
                
        setContentView(layout);
        layout.addView(contentTxt);
        
      this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
  int ratio = (level * 100) / scale;
contentTxt.setText(String.valueOf(ratio) + "%");
}
};