在 Android 中的特定电池电量上执行一段代码

Execute a piece of code on certain Battery Level in Android

我正在寻找一种方法,当 phone 电池寿命达到 10% 时,在我的 Android 应用程序中执行一段代码。谁能给我指出正确的操作方向?

像这样写一个接收器来获取电池电量:

public class BatteryReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    if (level < 10) {
        // Write your code here
    }
}

}

写一个服务:

public class BatteryService extends Service {

    private BatteryReceiver receiver;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        receiver = new BatteryReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

像这样在您的清单文件中注册此服务:

<service android:name="com.example.testandroid.BatteryService" >
    </service>

然后先启动服务Activity就够了。

以百分比形式获取电池电量

Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

float levelPert;
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

// Error checking that probably isn't needed but I added just in case.
if(level == -1 || scale == -1) {
    levelPert = 50.0f;
}

levelPert = ((float)level / (float)scale) * 100.0f; 

P.S。如文档中所述,BatteryManager 是粘性意图,因此无需添加清单声明。

您可以阅读有关获取电池的更多信息details here

来自 developer.android.com :

You can't easily continually monitor the battery state, but you don't need to.
Generally speaking, the impact of constantly monitoring the battery level has a greater impact on the battery than your app's normal behavior, so it's good practice to only monitor significant changes in battery level—specifically when the device enters or exits a low battery state.

来自this link