In BatteryLevelActivity.java
package com.android.checkbatterylevel;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class BatteryLevelActivity extends Activity {
/** Called when the activity is first created. */
public static TextView txt;
Button btn;
BatteryChangeReceiver batteryReceiver = null;
IntentFilter batFilter = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView)findViewById(R.id.text1);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { // TODO Auto-generated method stub
batteryReceiver = new BatteryChangeReceiver();
batFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, batFilter);
}
});
}
}
In BatteryChangeReceiver.java
package com.android.checkbatterylevel;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BatteryChangeReceiver extends BroadcastReceiver{
public final String ACTION1 = Intent.ACTION_BATTERY_CHANGED;
@Override
public void onReceive(Context arg0, Intent intent) {
if(intent.getAction().equals(ACTION1)){
int level = intent.getIntExtra("level", 0);
BatteryLevelActivity.txt.setText("Battery Level is-> " + level);
Log.e("Battery Level : "," : "+level);
}
}
}
In 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_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/text1"/>
<Button android:text="Check Battery Level"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
In AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.checkbatterylevel"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".BatteryLevelActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="BatteryChangeReceiver"></receiver>
</application>
</manifest>
Run the program you will get like this :
No comments:
Post a Comment