欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

AccessibilityService 类似微信自动抢红包的实现

程序员文章站 2022-03-14 19:57:44
类似微信抢红包也就是自动点击按钮实现1 创建一个类继承AccessibilityServicepublic class AutoClickService extends AccessibilityService { @Override public void onCreate() { super.onCreate(); } @Override protected void onServiceConnected() {...

类似微信抢红包也就是自动点击按钮实现

1 创建一个类继承AccessibilityService

public class AutoClickService extends AccessibilityService {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void onServiceConnected() {
         
        super.onServiceConnected();
    }

    private boolean onceClick = false;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
      

    }

    @Override
    public void onInterrupt() {
        
        
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        
    }

2 在Mainfest文件中配置service

<service
            android:name=".AutoClickService"
            android:label="点击测试"
            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/auto_click_service_config" />
        </service>

其中android:resource="@xml/auto_click_service_config"配置文件在AndroidStudio中res文件加下xml文件夹中创建auto_click_service_config.xml

如果res文件夹下面没有xml文件夹,可以新建res ——>Android Resources File ——> Resource type 选择xml创建即可。

auto_click_service_config.xml如下

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFeedbackType="feedbackSpoken"
    android:canRetrieveWindowContent="true"
    android:accessibilityFlags="flagDefault|flagRetrieveInteractiveWindows|flagIncludeNotImportantViews|flagReportViewIds"
    android:description="@string/auto_click_service_description"
    android:packageNames="com.sz.lyw.demoactivity"
    android:notificationTimeout="100" />

其中android:packageNames换成你想要监听的APP包名。

注意:很多时候无障碍权限是默认关闭的,需要先判断一下是否已打开该权限

public static boolean isAccessibilitySettingsOn(Context mContext, Class<? extends AccessibilityService> clazz) {
        int accessibilityEnabled = 0;
        final String service = mContext.getPackageName() + "/" + clazz.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

如果没有打开可以通过 startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)); 打开

AccessibilityService   类似微信自动抢红包的实现

在上面清单文件配置service时 android:label="点击测试" ,点击红色框,然后允许即可

3 如何点击指定按钮

前两步已经将service创建配置好,接下来就是如何点击指定按钮,处理是在我们自定义的AutoClickService类中

public class AutoClickService extends AccessibilityService {
    @Override
    public void onCreate() {
        super.onCreate();
        Utils.logPrint(" onCreate ");

    }

    @Override
    protected void onServiceConnected() {
       
        super.onServiceConnected();
    }

    private boolean onceClick = false;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
         
         AccessibilityOperate.getOperate().updateEvent(this, event);

         
         List<AccessibilityNodeInfo> accessibilityNodeInfos =
                 AccessibilityOperate.getOperate().findNodesByText("怎么着");


         AccessibilityOperate.getOperate().setAimVeiwList(accessibilityNodeInfos);

        
    }

    @Override
    public void onInterrupt() {
       
        Utils.logPrint(" onInterrupt ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
       
    }

}

其中AccessibilityOperate 是一个封装类 

public class AccessibilityOperate {

    public static AccessibilityOperate operate;

    public static AccessibilityOperate getOperate() {
        if (null == operate) {
            synchronized (AccessibilityOperate.class) {
                if (null == operate) {
                    operate = new AccessibilityOperate();
                }
            }
        }


        return operate;
    }


    private AccessibilityService mAccessibilityService;
    private AccessibilityEvent mAccessibilityEvent;

    public void updateEvent(AccessibilityService service, AccessibilityEvent event) {
        if (service != null && mAccessibilityService == null) {
            mAccessibilityService = service;
        }
        if (event != null) {
            mAccessibilityEvent = event;
        }
    }

    public List<AccessibilityNodeInfo> findNodesByText(String text) {
        Utils.logPrint("______________________START_________________________");
        AccessibilityNodeInfo nodeInfo = getRootNodeInfo();
        if (nodeInfo != null) {
            Utils.logPrint("toString:" + nodeInfo.toString());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                //需要在xml文件中声明权限android:accessibilityFlags="flagReportViewIds"
                // 并且版本大于4.3 才能获取到view 的 ID
                Utils.logPrint("getClassName:" + nodeInfo.getViewIdResourceName());
            }
            Utils.logPrint("______________________END_________________________");
            return nodeInfo.findAccessibilityNodeInfosByText(text);
        } else {
            Utils.logPrint("findNodesByText nodeInfo is null ");
        }
        return null;
    }

    public List<AccessibilityNodeInfo> findNodesById(String viewId) {
        AccessibilityNodeInfo nodeInfo = getRootNodeInfo();
        if (nodeInfo != null) {
            if (Build.VERSION.SDK_INT >= 18) {
                return nodeInfo.findAccessibilityNodeInfosByViewId(viewId);
            }
        }
        return null;
    }

    private AccessibilityNodeInfo getRootNodeInfo() {
        AccessibilityEvent curEvent = mAccessibilityEvent;
        AccessibilityNodeInfo nodeInfo = null;
        if (Build.VERSION.SDK_INT >= 16) {
            if (mAccessibilityService != null) {
                nodeInfo = mAccessibilityService.getRootInActiveWindow();
            }
        } else {
            nodeInfo = curEvent.getSource();
        }
        return nodeInfo;
    }


    private List<AccessibilityNodeInfo> nodeInfos;

    public void setAimVeiwList(List<AccessibilityNodeInfo> nodeInfos) {
        this.nodeInfos = nodeInfos;
    }


    public boolean performClick() {

        if (nodeInfos != null && !nodeInfos.isEmpty()) {
            Utils.logPrint(" size " + nodeInfos.size());
            AccessibilityNodeInfo node;
            for (int i = 0; i < nodeInfos.size(); i++) {
                node = nodeInfos.get(i);
                // 获得点击View的类型
                Utils.logPrint("node.toString():" + node.toString());
                // 进行模拟点击
                if (node.isEnabled()) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        return node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }
            }
        } else {
            Utils.logPrint(" nodeInfos is null or empty ");
        }
        return false;
    }

}

AccessibilityOperate.getOperate().findNodesByText("怎么着"); 是我监听的APP界面有一个Button,按钮的text是 怎么着;

AccessibilityService   类似微信自动抢红包的实现

其中 performClick()方法是在满足指定条件下调用;

我创建了一个AndroidAutoClickDemo的项目监听上图项目DemoActivity

然后在AndroidAutoClickDemo开启一个定时每6秒调用一次AccessibilityOperate.getOperate().performClick();

DemoActivity项目中就会在按钮被点击时弹出一个Toast;

具体点击策略视情况决定;

 

 

 

 

 

 

 

 

本文地址:https://blog.csdn.net/u011288271/article/details/107180593