当手机达到 10% 的电池寿命时,我正在寻找一种在我的 Android 应用程序中执行一段代码的方法。有人能指出我如何做到这一点的正确方向吗?
3 回答
以百分比获取电池电量
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;
PS 如文档中所述,BatteryManager 是粘性意图,因此无需添加清单声明。
您可以在此处阅读有关获取电池详细信息的更多信息
来自 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.
From this link
编写一个接收器来获取电池电量,如下所示:
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>
然后在 First Activity 中启动服务就足够了。