背景
我有一个应用程序有一个 AccessibilityService
. Android 似乎保持 AccessibilityService
它一直在运行,但我只需要运行我的有时。 (具体来说,如果用户打开我的应用并将其关闭,则不再需要 AccessibilityService
。)
如果我的AccessibilityService
在不需要时运行,它会浪费设备的 RAM 和 CPU,我想尽可能避免对我的用户这样做。
问题
如何以编程方式启动和停止我的 AccessibilityService
?
请注意,我不是要求以编程方式启用或禁用 AccessibilityService
在 Android 的辅助功能设置中;这只是关于在它已启用时启动和停止它。
我试过的(停止 AccessibilityService
)
禁用
AccessibilityService
使用以下组件:PackageManager.setComponentEnabledSetting( accessibilityServiceName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0 );
这杀死了整个应用程序,包括
AccessibilityService
.此外,重启手机后,AccessibilityService
在 Android 辅助功能设置中不再可见。 (似乎需要重新启用该组件,然后重新启动手机才能使其再次显示。)禁用
AccessibilityService
使用以下组件:PackageManager.setComponentEnabledSetting( accessibilityServiceName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP );
这并没有阻止
AccessibilityService
.停止
AccessibilityService
使用Context.stopService()
和Service.stopSelf()
. 这些并没有停止服务,大概是because the OS is bound to it .杀死
AccessibilityService
使用Process.killProcess()
的过程.但是,该服务在重新启动并重新连接后不久就出现了,大概是因为操作系统已绑定(bind)到它。使用
AccessibilityService.setServiceInfo(new AccessibilityServiceInfo())
注销辅助功能事件.这会阻止该服务获取辅助功能事件,但该服务仍在后台运行。
相关问题
Can accessibility service be stopped or killed?
这只是关于停止服务。我希望能够在服务停止后再次启动该服务。
最佳答案
取自the Lifecycle section of the AccessibilityService
documentation :
The lifecycle of an accessibility service is managed exclusively by the system and follows the established service life cycle. Starting an accessibility service is triggered exclusively by the user explicitly turning the service on in device settings. After the system binds to a service, it calls
onServiceConnected()
. This method can be overriden by clients that want to perform post binding setup.An accessibility service stops either when the user turns it off in device settings or when it calls
disableSelf()
(In Android 7.0 (API 24) and later).
关于android - 如何以编程方式启动和停止 AccessibilityService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40433449/