如何以编程方式启动和停止 AccessibilityService?

How can I programmatically start and stop an AccessibilityService?

背景

我有一个不再需要 AccessibilityService. Android seems to keep AccessibilityServices running all the time, but I only need mine to run sometimes. (Specifically, if a user opens my app and turns it off, the AccessibilityService 的应用程序。)

如果我的 AccessibilityService 在不需要时是 运行,它会浪费设备的 RAM 和 CPU,我想尽可能避免对我的用户这样做。

问题

如何以编程方式启动和停止我的 AccessibilityService

请注意,我不是要求以编程方式启用或禁用Android的辅助功能设置中的AccessibilityService;这只是在它已经启用时启动和停止它。

我试过的方法(停止 AccessibilityService

相关问题

取自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).

如 Sam 的回答所述,AccessibilityService 的生命周期由系统专门管理,因此您无法终止它。

但是除了资源优化的目的之外,如果您仍然需要 start/stop AccessibilityService 在某些情况下运行,您可以简单地使用旧的 SharedPreferences

您服务的 onAccessibilityEvent 应该是:

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    if (prefs.getBoolean("isServiceEnabled", true)){
        /*
        * Your code goes here
        */
    }
}

当您想要 "switch off/on" 服务时,您可以根据需要在某个按钮的 onClickListener 或其他地方简单地编写此服务:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

prefs.edit().putBoolean("isServiceEnabled", false).apply(); // disable

prefs.edit().putBoolean("isServiceEnabled", true).apply();  // enable