3

我正在使用此代码来跟踪我的服务中的电池信息:

    Intent i = new ContextWrapper(applicationContext).registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
     // now you can get the level and scale from this intent variable
    int level = i.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = i.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

float battPct = level/(float)scale;

1.我想知道它是否会自动更换然后更换电池?还是我需要自己定期触发该意图?2. 另外我想知道是否有一种方法可以计算自使用了 1% 的剩余电池以来经过了多少时间。

4

2 回答 2

9

Better way to get change value you should use BroadcastReceiver.

To get changed value when battery change. You need to use BroadCastReceiver.

IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);

BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent){
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float battPct = level/(float)scale;       
    }
};
于 2013-03-09T17:33:30.157 回答
0

以下事情对我有用:

在清单文件中,查找**<activity android:name=".MainActivity">** 并替换为***<activity android:name=".MainActivity" android:exported="true">***

于 2021-12-19T16:11:32.263 回答