How to Programmatically Enable/Disable Accessibility Service in Android

后端 未结 9 534
暗喜
暗喜 2020-11-27 15:38

I would like to programmatically enable/disable Accessibility Services listed under Settings->Accessibility option.

I could start Accessibility Intent like below:

9条回答
  •  抹茶落季
    2020-11-27 15:57

    Here is the working solution (if your activity is not running it will disable itself)

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Toast.makeText(this, "Connected!",Toast.LENGTH_SHORT).show();
        ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
            public void run() {
                serviceChecker();
            }
        }, 0, 5, TimeUnit.SECONDS);
    }
    
    private void serviceChecker(){
        if(!isActivityRunning(MainActivity.class)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                disableSelf();
            }
        }
    }
    protected Boolean isActivityRunning(Class activityClass)
    {
        ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
        List tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
    
        for (ActivityManager.RunningTaskInfo task : tasks) {
            if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName()))
                return true;
        }
    
        return false;
    }
    

提交回复
热议问题