Tuesday, September 7, 2010

Detect Battery Level

It's a exercise of Android App to detect battery level.

Detect Battery Level

A BroadcastReceiver, myBatteryReceiver, is implemented and registered to receive ACTION_BATTERY_CHANGED, and retrieve "level" via getIntExtra() method.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/batterylevel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Level:"
/>
</LinearLayout>


AndroidBattery.java
package com.exercise.AndroidBattery;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidBattery extends Activity {

private TextView batteryLevel;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

batteryLevel = (TextView)findViewById(R.id.batterylevel);
this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

private BroadcastReceiver myBatteryReceiver
= new BroadcastReceiver(){

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int bLevel = arg1.getIntExtra("level", 0);

batteryLevel.setText("Battery Level: "
+ String.valueOf(bLevel) + " %");
}

};
}


Download the files.

Related Article: Detect Battery Info.

No comments: