AccessibilityService 检测正在运行的程序

##AccessibilityService 无障碍/辅助功能

##使用这个服务需要用户手动授权

 

Demo:监听当前正在运行的程序

 

1.创建DetectionService继承 AccessibilityService

 

@Override

public void onAccessibilityEvent(AccessibilityEvent event) {

 if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {

            /*

             * 如果 与 DetectionService 相同进程,直接比较 foregroundPackageName 的值即可

             * 如果在不同进程,可以利用 Intent bind service 进行通信

             */

            foregroundPackageName = event.getPackageName().toString();

 

            /*

             * 基于以下还可以做很多事情,比如判断当前界面是否是 Activity,是否系统应用等,

             * 与主题无关就不再展开。

             */

            ComponentName cName = new ComponentName(event.getPackageName().toString(),

                    event.getClassName().toString());

        }

}

 

@Override

public void onInterrupt() {

// TODO Auto-generated method stub

}

 

2.res文件下创建xml文件,同时创建.xml文件

 

"1.0" encoding="utf-8"?>

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:accessibilityEventTypes="typeWindowStateChanged"

    android:accessibilityFeedbackType="feedbackGeneric"

    android:accessibilityFlags="flagIncludeNotImportantViews" />

 

3.在配置文件中声明该service

 

            android:name=".DetectionService"

            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" >

            

                "android.accessibilityservice.AccessibilityService" />

            

 

            

                android:name="android.accessibilityservice"

                android:resource="@xml/accessibility" />

        

4.工具方法

 

 /**

     * 方法6:使用 Android AccessibilityService 探测窗口变化,跟据系统回传的参数获取 前台对象 的包名与类名

     *

     * @param packageName 需要检查是否位于栈顶的App的包名

     */

    public static String isForegroundPkgViaDetectionService() {

//        return packageName.equals(DetectionService.foregroundPackageName);

        return DetectionService.foregroundPackageName;

}

 

5.检测是否开启了‘无障碍、辅助功能’

 

// 此方法用来判断当前应用的辅助功能服务是否开启

    public static boolean isAccessibilitySettingsOn(Context context) {

        int accessibilityEnabled = 0;

        try {

            accessibilityEnabled = Settings.Secure.getInt(context.getContentResolver(),

                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);

        } catch (Settings.SettingNotFoundException e) {

            Log.i("URL", "错误信息为:"+e.getMessage());

        }

 

        if (accessibilityEnabled == 1) {

            String services = Settings.Secure.getString(context.getContentResolver(),

                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);

            if (services != null) {

                return services.toLowerCase().contains(context.getPackageName().toLowerCase());

            }

        }

        return false;

    }

 

说明:





 

    

 

你可能感兴趣的:(Android)