如何将电池百分比值设为int值

时间:2015-06-01 12:54:31

标签: android

我希望将电池信息接收到文本类型和" level"的值。无法在广播接收器外访问。如何在代码中访问广播接收器的电平值,以便在oncreate方法中使用它

    public BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context ctxt, Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        batteryTxt.setText(String.valueOf(level) + "");


    }
};

2 个答案:

答案 0 :(得分:0)

如获取battery level only once using Android SDK中所述您可以使用以下代码:

 Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
 int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

答案 1 :(得分:0)

在你的oncreate方法中使用它:

在oncreate中声明你的textview

this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

在该活动中实施接收器

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
                    @Override
                    public void onReceive(Context ctxt, Intent intent) {
                      int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                      Log.e("ebre", level+"**");
            batteryTxt.setText(String.valueOf(level) + "");
                    }
                  };

修改

只要您想激活接收器,只需使用它来呼叫接收器

this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

如果您想要电池百分比,请在活动中声明它并使用该值。