Loading

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.

SHARE TWEET

Thank you for reading this article Detect Battery Level With URL https://x-tutorials.blogspot.com/2010/09/detect-battery-level.html. Also a time to read the other articles.

0 comments:

Write your comment for this article Detect Battery Level above!