This code monitor battery level by registering our BroadcastReceiver with IntentFilter for Intent.ACTION_BATTERY_CHANGED.
![Monitor battery level of Android device Monitor battery level of Android device](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi2BUTPo7rxhg4yF1OOY5kY8eqONOf0dRLbeD1JYdA9EYbevcZbUkomk-8_0OvqE6sqzANKJ-YogQKFX0smatRThM6GVaAV_bdu7evFGoKQkbtsaXBMqcx33X4zXjhDiD611sHQl4Am3jph/s400/AndroidBattery_01.png)
package com.example.androidbattery;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView batteryStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
batteryStatus = (TextView)findViewById(R.id.batterystatus);
IntentFilter batteryFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryMonitor, batteryFilter);
}
private BroadcastReceiver batteryMonitor
= new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
int batteryLevel = arg1.getIntExtra("level", 0);
batteryStatus.setText("Battery level = " + String.valueOf(batteryLevel) + "%");
}};
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<TextView
android:id="@+id/batterystatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
No comments:
Post a Comment