我正在使用此代码在我的应用程序中显示电池电量。它工作正常,但不会自动更新电池电量。
我应该怎么做才能自动更新电池电量。
public class MainActivity extends Activity {
private TextView txtBattery;
private BroadcastReceiver mBatteryLevelReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
//int rawLevel = intent.getIntExtra("level", -1);
int rawLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
//int scale = intent.getIntExtra("scale", -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawLevel >= 0 && scale > 0) {
level = (rawLevel * 100) / scale;
}
txtBattery.setText("Battery3 Level Remaining :" + level + "%");
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtBattery = (TextView) findViewById(R.id.batterymeter_txt);
batteryLevel();
}
private void batteryLevel() {
IntentFilter batteryLevelFliter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(mBatteryLevelReciver, batteryLevelFliter);
}
}