在系统中,当前电池电量的广播如下:
Intent.Action_Battery_Changed
前两个使用系统广播的例子都是在mainfirst中配置receive。这次我们在程序中注册,同时使用匿名类来实现BroadcastReceiver。
public class Main extends Activity
{
private TextView tvBatteryChanged;
private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver()
{
@Override
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) + "%");
}
}
};
@Override
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));
}
}
其中level表示当前电量的值,scale表示电量的总刻度。