在 Oreo 上 ACTION_POWER_CONNECTED 启动 activity 是否有解决方法?

Is there a workaround for launching an activity at ACTION_POWER_CONNECTED on Oreo?

我目前正在为客户端开发一个应用程序,该应用程序应该在充电时启动。我知道这样做的唯一方法是像这样使用清单:

<intent-filter>
    <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
    <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>

但是对于 Android Oreo,这不再是一个有效的选项,并导致按照 "Background execution not allowed".

行打印错误

有没有人找到解决这个问题的好方法?本质上,我需要一种在连接电源时启动 activity 并使其保持打开状态直到电源断开的方法。 phone 不会是 运行 我可以用来创建显式广播的任何其他服务或活动。

But for Android Oreo, this is no longer a valid option and causes an error to print along the lines of "Background execution not allowed".

来自 Oreo 当应用程序处于前台时,它可以自由地创建和 运行 前台和后台服务。因此,一种可能的方法是创建一个 foreground service,它使用 BatteryManager class 监控 charging/not 充电状态 - 这个 class 广播所有电池和充电详细信息包含充电状态的粘性 Intent。

val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus = context.registerReceiver(null, ifilter)

 val status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
 val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL

现在您知道您的设备是否正在充电了。

来自同一服务的下一个 class 代码 - 基于充电状态 - 您可以启动 YourActivity,如下所示,

Intent i = new Intent();
i.setClass(this, YourActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

现在开始这样的 activity 可能不是最好的用户体验 - 因此您可能需要考虑使用 android 的通知系统向 update/inform 用户发送有关状态的信息充电