如何在Android 8上广播ACTION_POWER_CONNECTED [英] How to get broadcast ACTION_POWER_CONNECTED on Android 8

查看:139
本文介绍了如何在Android 8上广播ACTION_POWER_CONNECTED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个在一天的特定时间段内将手机连接至充电器时显示一些信息的应用程序.

I am trying to make an app that shows some information when you connect your phone to a charger during a specific period of the day.

在使用Android Oreo之前,这很容易,只需添加一个Broadcast接收器,然后将android.intent.action.ACTION_POWER_CONNECTED添加到清单中的intentfilter.

Before Android Oreo this was easy, just add an Broadcast receiver and add android.intent.action.ACTION_POWER_CONNECTED to the intentfilter in the manifest.

现在,我正在努力寻找一种可行的解决方案来创建相同的功能. 我曾想过要定期检查设备的充电状态,但这感觉很不好,并且在将设备连接到充电器时不会立即触发.

Now I am struggling to find a working solution to create the same functionality. I thought about periodically checking the device charging state but this feels wrong and it won't trigger immediately on connecting the device to a charger.

从我的应用程序注册广播接收器也不起作用,当应用程序关闭时,不再接收广播.

Registering the broadcast receiver from my application did not work either, when the application is closed the broadcast isn't received anymore.

将Android设备连接到Android Oreo中的充电器时,是否存在电池友好的方式来触发动作?

Is there a battery friendly way to trigger an action when an Android device is connected to a charger in Android Oreo?

推荐答案

广播不受后台执行限制的限制,并且哪些广播接收者仍可以在清单中注册.

There are broadcasts which are exempted from the background execution limitations and for which broadcast receivers can still be registered in the manifest.

您可以使用ACTION_BOOT_COMPLETED广播来启动一项服务,该服务在运行时为ACTION_POWER_CONNECTED广播注册一个接收器. (该服务必须是前台服务.否则,它可能会被破坏.)

You could use the ACTION_BOOT_COMPLETED broadcast to start a service which registers a receiver for your ACTION_POWER_CONNECTED broadcast at runtime. (The service must be a foreground service. Otherwise, it may be destroyed.)

另一种解决方案是使用JobScheduler创建一个

A other solution would be to use JobScheduler to create a job which requires charging. Then you don't need the foreground service.

这篇关于如何在Android 8上广播ACTION_POWER_CONNECTED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆