Android 辅助服务与悬浮窗

8,253 阅读8分钟

第一节

本文旨在介绍AccessibilityService如果更优雅的使用,以及使用过程遇到的问题,该怎么解决。

一、介绍

辅助功能服务在后台运行,并在触发AccessibilityEvent时由系统接收回调。这样的事件表示用户界面中的一些状态转换,例如,焦点已经改变,按钮被点击等等。现在常用于自动化业务中,例如:微信自动抢红包插件,微商自动加附近好友,自动评论朋友,点赞朋友圈,甚至运用在群控系统,进行刷单

二、配置

1、新建Service并继承AccessibilityService

    /**
     * 核心服务:执行自动化任务
     * Created by czc on 2017/6/13.
     */
    public class TaskService_ extends AccessibilityService{
        @Override
        public void onAccessibilityEvent(AccessibilityEvent event) {
            //注意这个方法回调,是在主线程,不要在这里执行耗时操作
        }
        @Override
        public void onInterrupt() {
    
        }
    }

2、并配置AndroidManifest.xml

    <service
        android:name=".service.TaskService"
        android:enabled="true"
        android:exported="true"
        android:label="@string/app_name_setting"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService"/>
        </intent-filter>

        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/accessibility"/>
    </service>

3、在res目录下新建xml文件夹,并新建配置文件accessibility.xml

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    <!--监视的动作-->
    android:accessibilityEventTypes="typeAllMask"
    <!--提供反馈类型,语音震动等等。-->
    android:accessibilityFeedbackType="feedbackGeneric"
     <!--监视的view的状态,注意这里设置flagDefault会到时候部分界面状态改变,不触发onAccessibilityEvent(AccessibilityEvent event)的回调-->
    android:accessibilityFlags="flagDefault|flagRetrieveInteractiveWindows|flagIncludeNotImportantViews|flagReportViewIds|flagRequestTouchExplorationMode"
    <!--是否要能够检索活动窗口的内容,此设置不能在运行时改变-->
    android:canRetrieveWindowContent="true"
    <!--功能描述-->
    android:description="@string/description"
    <!--同一事件间隔时间名-->
    android:notificationTimeout="100" 
    <!--监控的软件包名-->
    android:packageNames="com.tencent.mm,com.eg.android.AlipayGphone" />

三、核心方法

1、根据界面text找到对应的组件(注:方法返回的是集合,找到的组件不一点唯一,同时这里的text不单单是我们理解的 TextView 的 Text,还包括一些组件的 ContentDescription)

accessibilityNodeInfo.findAccessibilityNodeInfosByText(text)

2、根据组件 id 找到对应的组件(注:方法返回的是集合,找到的组件不一点唯一,组件的 id 获取可以通过 Android Studio 内置的工具 monitor 获取,该工具路径:C:\Users\Dell\AppData\Local\Android\Sdk\tools)

accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id)

image

四、辅助权限判断是否开启

    public static boolean hasServicePermission(Context ct, Class serviceClass) {
        int ok = 0;
        try {
            ok = Settings.Secure.getInt(ct.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
        }

        TextUtils.SimpleStringSplitter ms = new TextUtils.SimpleStringSplitter(':');
        if (ok == 1) {
            String settingValue = Settings.Secure.getString(ct.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                ms.setString(settingValue);
                while (ms.hasNext()) {
                    String accessibilityService = ms.next();
                    if (accessibilityService.contains(serviceClass.getSimpleName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

五、辅助的开启方法

1.root 授权环境下,无需引导用户到系统设置页面开启

    public static void openServicePermissonRoot(Context ct, Class service) {
        String cmd1 = "settings put secure enabled_accessibility_services  " + ct.getPackageName() + "/" + service.getName();
        String cmd2 = "settings put secure accessibility_enabled 1";
        String[] cmds = new String[]{cmd1, cmd2};
        ShellUtils.execCmd(cmds, true);
    }

2.targetSdk 版本小于23的情况下,部分手机也可通过以下代码开启权限,为了兼容,最好 try...catch 以下异常

    public static void openServicePermission(Context ct, Class serviceClass) {
        Set<ComponentName> enabledServices = getEnabledServicesFromSettings(ct, serviceClass);
        if (null == enabledServices) {
            return;
        }
        ComponentName toggledService = ComponentName.unflattenFromString(ct.getPackageName() + "/" + serviceClass.getName());
        final boolean accessibilityEnabled = true;
        enabledServices.add(toggledService);
        // Update the enabled services setting.
        StringBuilder enabledServicesBuilder = new StringBuilder();
        for (ComponentName enabledService : enabledServices) {
            enabledServicesBuilder.append(enabledService.flattenToString());
            enabledServicesBuilder.append(":");
        }
        final int enabledServicesBuilderLength = enabledServicesBuilder.length();
        if (enabledServicesBuilderLength > 0) {
            enabledServicesBuilder.deleteCharAt(enabledServicesBuilderLength - 1);
        }
        Settings.Secure.putString(ct.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, enabledServicesBuilder.toString());
        // Update accessibility enabled.
        Settings.Secure.putInt(ct.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, accessibilityEnabled ? 1 : 0);
    }

    public static Set<ComponentName> getEnabledServicesFromSettings(Context context, Class serviceClass) {
        String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        if (enabledServicesSetting == null) {
            enabledServicesSetting = "";
        }
        Set<ComponentName> enabledServices = new HashSet<ComponentName>();
        TextUtils.SimpleStringSplitter colonSplitter = new TextUtils.SimpleStringSplitter(':');
        colonSplitter.setString(enabledServicesSetting);
        while (colonSplitter.hasNext()) {
            String componentNameString = colonSplitter.next();
            ComponentName enabledService = ComponentName.unflattenFromString(componentNameString);
            if (enabledService != null) {
                if (enabledService.flattenToString().contains(serviceClass.getSimpleName())) {
                    return null;
                }
                enabledServices.add(enabledService);
            }
        }
        return enabledServices;
    }

3.引导用户到系统设置界面开启权限

    public static void jumpSystemSetting(Context ct) {
        // jump to setting permission
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ct.startActivity(intent);
    }

4.结合一起,我们可以这样开启辅助权限

    public static void openServicePermissonCompat(final Context ct, final Class service) {
        //辅助权限:如果root,先申请root权限
        if (isAppRoot()) {
            if (!hasServicePermission(ct, service)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        openServicePermissonRoot(ct, service);
                    }
                }).start();
            }
        } else {
            try {
                openServicePermission(ct, service);
            } catch (Exception e) {
                e.printStackTrace();
                if (!hasServicePermission(ct, service)) {
                    jumpSystemSetting(ct);
                }
            }
        }
    }

第二节

在执行自动化服务的流程中,我们其实并不希望被用户的操作中断流程,所以有什么方法在用户点击自动化操作的过程中,避免用户再次操作呢?那就是开启一个全局透明的悬浮窗,进行屏蔽触摸事件。

一、悬浮窗

其实一开始,我是想当然的跟以前一样,开启一个全屏的透明的悬浮窗,进行遮罩的作用,但是发现,设置 Type 为 TYPE_TOAST 或者 TYPE_SYSTEM_ALERT 这样的悬浮窗某些类型的不同,会导致不单单把用户的操作屏蔽了,甚至窗口的一些状态改变也屏蔽的,导致辅助权限的 onAccessibilityEvent() 方法不回调,于是去找官方文档,查找相关悬浮窗的 Type 类型设置。然后被我找到这个属性值的 Type :

LayoutParams.TYPE_ACCESSIBILITY_OVERLAY

我们再来看官方解释:

Windows that are overlaid only by a connected AccessibilityService for interception of user interactions without changing the windows an accessibility service can introspect. In particular, an accessibility service can introspect only windows that a sighted user can interact with which is they can touch these windows or can type into these windows. For example, if there is a full screen accessibility overlay that is touchable, the windows below it will be introspectable by an accessibility service even though they are covered by a touchable window.

虽然官方写的一大堆,但是我们大概能 get 到里面的意思,其实就是设置为这个类型的悬浮窗,能够使辅助功能继续响应相关窗口与内容的变化。经测试,果然设置这个类型的悬浮窗,可以一方面屏蔽用户的触摸事件,另一方继续响应自动点击的相关操作。

    public void createFullScreenView(Context context) {
        WindowManager windowManager = getWindowManager(context);
        if (fullScreenView == null) {
            fullScreenView = new FloatWindowFullScreenView(context);
            LayoutParams fullScreenParams = new LayoutParams();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                fullScreenParams.type = LayoutParams.TYPE_ACCESSIBILITY_OVERLAY;
            } else {
                fullScreenParams.type = LayoutParams.TYPE_TOAST;
            }
            fullScreenParams.format = PixelFormat.TRANSLUCENT;
            fullScreenParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
            fullScreenParams.gravity = Gravity.CENTER;
            windowManager.addView(fullScreenView, fullScreenParams);
        }
    }

值得注意的是,这个属性是在 android 5.1 之后加入进来,对于之前的版本,经测试,使用 Toast 类型,也能执行相关操作,至于为什么 5.1 之后不继续使用Toast类型呢,这里面涉及到悬浮窗的开启问题了,可自行百度悬浮窗的开启相关文章。

二、悬浮窗的 Context

我们一般开启悬浮窗的过程中,Context 的传递我们使用的 Service 或者 Activity,不过如果设置为 TYPE_ACCESSIBILITY_OVERLAY 的悬浮窗,是只能传入你继承自 AccessibilityService 的服务(Context,否则会报 Is Activity Running 这个异常,那如何在这个服务里面开启悬浮窗呢?我是使用广播的形式去开启的:

    // 注册广播接听者
    IntentFilter filter = new IntentFilter();
    filter.addAction(Const.ACTION_SHOW_COVER_VIEW);
    filter.addAction(Const.ACTION_SHOW_SMALL_VIEW);
    filter.addAction(Const.ACTION_SET_COVER_VIEW_TIPS);
    registerReceiver(mReceiver, filter);
        
    ....省略其他代码
    
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Const.ACTION_SHOW_COVER_VIEW)) {
                if (!FloatWindowManager.getInstance().isFullWindowShowing()) {
                    FloatWindowManager.getInstance().createFullScreenView(TaskService.this);
                }
                String toast = intent.getStringExtra(Const.EXTRA_WINDOW_TOAST);
                if (!StringUtils.isEmpty(toast)) {
                    FloatWindowManager.getInstance().showToast(toast);
                }
            } else if (action.equals(Const.ACTION_SHOW_SMALL_VIEW)) {
                if (!FloatWindowManager.getInstance().isSmallWindowShowing()) {
                    FloatWindowManager.getInstance().createSmallWindow(TaskService.this);
                }
            }else if (action.equals(Const.ACTION_SET_COVER_VIEW_TIPS)) {
                if (FloatWindowManager.getInstance().isFullWindowShowing()) {
                    FloatWindowManager.getInstance().showTipst(intent.getStringExtra("tips"));
                }
            }
        }
    };

三、悬浮窗开启引导

为了更好的用户体验,我们需要给我们每一步操作一个明确的提示,让用户知道需要做些什么,特别是引导开启系统权限的时候。

关于悬浮窗的开启,之前有写过一篇文章,Android 悬浮窗踩坑体验,里面有介绍关于悬浮窗的开启、权限以及自定义悬浮窗。不过这里我要介绍的是另一种特殊的技巧,在没有开启悬浮窗权限的情况下,用一个特殊的 Activity 来代替悬浮窗。先介绍两个 Activity 在 AndroidManifest 属性:

1、taskAffinity

简单讲一下这个属性的意思:默认情况下,我们启动的 Activity 都是归属于同包名的任务栈里面,但如果配置这个属性,则该 Activity 会在新的任务栈里面(栈名是你配置的)

android:taskAffinity=".guide"

可以通过以下命令去查看当前任务栈的信息:

adb shell dumpsys activity activities

2、excludeFromRecents

当配置这个属性,可以让你的 Activity 不会出现在最近任务列表里面

android:excludeFromRecents="true"

3、配置 Activity 主题是全屏透明

android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"

为什么要配置这两个属性呢? 因为我们不希望这个特殊的Activity出现在最近的使用列表里面,同时配置 taskAffinity 是为了让这个 Activity 在新的任务栈里面,使得它在 finish 的时候,不是回到我们之前启动过的前一个 Activity (并不想影响我们之前的任务栈),这样的做法就能够在其他 App 界面显示我们的 Activity,需要特别说明的的是:启动该 Acitivity 需要配合 Intent.FLAG_ACTIVITY_NEW_TASK 标识启动。代码如下:

<activity
    android:name="com.czc.ui.act.GuideActivity"
    android:taskAffinity=".guide"
    android:excludeFromRecents="true"
    android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
</activity>

完整代码:

public class GuideActivity extends Activity {

    public static void start(Activity act, String message) {
        Intent intent = new Intent(act, GuideActivity.class);
        intent.putExtra("message", message);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        act.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);

        //设置Activity界面大小
        Window window = getWindow();
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        WindowManager.LayoutParams params = window.getAttributes();
        params.x = 0;
        params.y = 0;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.height = ScreenUtil.dip2px(80);
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(params);

        TextView tvMessage = findViewById(R.id.tv_message);
        tvMessage.setText(getIntent().getStringExtra("message"));

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
            // 5s 后自动关闭提示
                finish();
            }
        }, 5000);
    }
}

4、界面呈现的效果

1.检测到没有【悬浮窗权限】或者【辅助权限】,弹出权限设置页面 PermissionActivity

PermissionActivity

2.跳转系统设置里面的同时【弹出】 GuideActivity

GuideActivity

四、悬浮窗的实现

在悬浮窗的UI设计上,我们需要将其设置为透明背景,这样对用户是无感的,整个自动化流程中,其实是相当于屏幕有个用户看不到的“保护罩”在确保着你的自动化业务不被“打扰”。在布局上,我们需要实现最外层的根布局的点击事件,这样在用户点击屏幕的时候,弹窗 Toast 友好提示用户:自动化业务正在执行,请停止业务才能操作。

image

同时悬浮窗提供“停止”按钮,可以终止业务并关闭全屏透明悬浮窗。

五、使用场景

部分软件需要开启许多权限才能保证软件的正常使用,例如市面上的某锁屏软件,他们需要涉及相当多的权限,如果一个个让用户去开启,可能找不到对应的权限怎么开启,于是他们把这个流程简化成脚本,只要用户开启辅助权限,则跳转到权限开启流程,自动到权限页面,把例如:开机自启动权限,读取通知,获取位置等权限开启。当然这个过程是被一个界面遮盖了的,用户是看不到执行了什么操作的(这也暴露android的安全性问题)。

image