How can I programmatically start and stop an AccessibilityService?

試著忘記壹切 提交于 2019-12-04 13:49:59

Taken from 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().

As stated in Sam's answer, the lifecycle of an AccessibilityService is managed exclusively by the system, so you can't kill it.

But apart resource optimization aims, if you still need to start/stop the AccessibilityService from operating in some circumstances, you can simply use the good old SharedPreferences.

Your Service's onAccessibilityEvent should be:

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

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

When you want to "switch off/on" the service you can do it by simply writing this in some button's onClickListener or somewhere else according to your needs:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

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

prefs.edit().putBoolean("isServiceEnabled", true).apply();  // enable
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!