业余时间写了一个小程序,怎么获取手机电池的当前电量
2:功能代码BatteryActivity.java
3:运行如图:
1:先看它的布局代码,有点简单layout/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:id="@+id/tvBatteryChanged"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
/>
</LinearLayout>
<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:id="@+id/tvBatteryChanged"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
/>
</LinearLayout>
package com.android.test;
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 BatteryActivity extends Activity {
private TextView tvBatteryChanged;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvBatteryChanged = (TextView)findViewById(R.id.tvBatteryChanged);
//注册一个接受广播类型
registerReceiver(batteryChangedReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
//接受广播
private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
int level = intent.getIntExtra( "level", 0);
int scale = intent.getIntExtra( "scale", 100);
tvBatteryChanged.setText( "电池电量:" + (level * 100 / scale) + "%");
}
}
};
}
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 BatteryActivity extends Activity {
private TextView tvBatteryChanged;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvBatteryChanged = (TextView)findViewById(R.id.tvBatteryChanged);
//注册一个接受广播类型
registerReceiver(batteryChangedReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
//接受广播
private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
int level = intent.getIntExtra( "level", 0);
int scale = intent.getIntExtra( "scale", 100);
tvBatteryChanged.setText( "电池电量:" + (level * 100 / scale) + "%");
}
}
};
}
程序有点简单,业余时间玩玩,希望大家喜欢
本文转自 Art_Hero 51CTO博客,原文链接:http://blog.51cto.com/curran/524985,如需转载请自行联系原作者