This code monitor battery level by registering our BroadcastReceiver with IntentFilter for Intent.ACTION_BATTERY_CHANGED.
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>
0 Response to "Monitor battery level"
Posting Komentar