gpt4 book ai didi

Android:在特定电池电量下启动服务

转载 作者:行者123 更新时间:2023-11-29 21:06:56 25 4
gpt4 key购买 nike

如果充电时电池电量达到特定值,我想启动一个 IntentService。

但是,我不想在 AndroidManifest.xml 中为 android.intent.action.BATTERY_CHANGED 注册一个 BroadcastReceiver,因为我需要服务仅在一定水平(例如 40%)且仅在充电时开始。

另一个想法是启动一项服务,该服务只要手机充电就运行,并以编程方式注册接收器。第三个想法是使用 AlarmManager 定期启动服务并检查电池电量。

什么是最好的方法?

解决方案:
我已经从下面的答案中实现了第四个想法。

final int PI_REQUEST_CODE = 123456;
int pref_BatteryUpdatePeriod = 120000; // 2 minutes

// set repeating alarm manager
Intent monitorIntent = new Intent(this, CheckBatteryReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), PI_REQUEST_CODE, monitorIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().get(Calendar.MILLISECOND), pref_BatteryUpdatePeriod, pendingIntent);

和警报的广播接收器:

public class CheckBatteryReceiver extends BroadcastReceiver {

private int targetBatterylevel = 40;

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

// get sticky intent
Intent batteryStatusIntent = context.getApplicationContext()
.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int batteryLevel = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 50);

// evaluate battery level
if(batteryLevel >= targetBatterylevel){
// start service to stop charging
} else {
// continue charging
}
}
}

注意:我必须使用 context.getApplicationContext() 而不是 context 否则应用程序会崩溃,但我无法在 broadcastreceiver 中注册接收器

最佳答案

I dont want to register a BroadcastReceiver for android.intent.action.BATTERY_CHANGED in the AndroidManifest.xml because i need the service only started at a certain level (e.g. 40%) and only while charging.

无论如何这都行不通,因为您无法在 list 中注册该广播。

Another idea would be starting a service that runs as long as the phone is charged and register a receiver programmatically.

恶心。

A third idea would be to periodically start a service with AlarmManager and check battery level.

第四个想法是使用 AlarmManager ,正如您所建议的,但从一开始就绕过该服务。只要有 AlarmManager调用 BroadcastReceiver .它可以通过调用context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED))来检查电池电量。 (在 context 上传递到 onReceive() )。 IntentregisterReceiver() 返回将是ACTION_BATTERY_CHANGED的最后一次播出.如果电池电量处于或低于您想要的阈值,则启动您的 IntentService .您可能需要采用 WakefulBroadcastReceiverWakefulIntentService如果您的闹钟会唤醒设备,请使用模式。还允许用户选择轮询周期,以便他们可以牺牲精度以获得更好的设备性能。

我会选择第四个想法。

关于Android:在特定电池电量下启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24261440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com