AccessibilityService模拟点击&获取页面内容

AccessibilityService模拟点击&获取页面内容

十二月 14, 2018

#模拟点击,自动生成某宝二维码,下面是一种方法,更优化的需要自己去改进,我在这里写一下最基础的

##AccessibilityService 这个方法是为残疾准备的,所以需要开启”无障碍开关来监听界面的窗口”,可以模仿点击登录、抢红包、刷票、各种你想不到的。

###findAccessibilityNodeInfosByViewId 里面的id需要用AndroidStudio的 AndroidDeviceMonitor 截取

###findAccessibilityNodeInfosByViewText 里面直接写需要点击的控件名字,比如”登录”

1:首先要写一个服务实现##AccessibilityService;如下

public class AutoClickService extends AccessibilityService {
private static final String TAG = "GK";
public static boolean state1=false;
public static boolean state2=false;
public static boolean state3=false;
public static boolean state4=false;
public static boolean state5=false;
public static boolean state6=false;
public static boolean alipayType=true;

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

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    int eventType = event.getEventType();
    AccessibilityNodeInfo rootInfo = getRootInActiveWindow();
    AccessibilityNodeInfo mNodeInfo = event.getSource(); 

    switch (eventType) {
        case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:  //收到通知栏消息
            Log.e("收到通知栏消息","收到通知栏消息");
            break;
        case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:    //界面状态改变
            Log.e("界面状态改变","界面状态改变");
            break;
        case  AccessibilityEvent.TYPE_VIEW_CLICKED:   //点击事件
            Log.e("点击事件","点击事件");
            break;
        case AccessibilityEvent.CONTENT_CHANGE_TYPE_TEXT: //文本改变
            Log.e("文本改变","文本改变");
            break;
        case AccessibilityEvent. TYPE_VIEW_HOVER_EXIT: //
            Log.e("最后一个窗口","最后一个窗口");
            break;
    }

    try {

        if (rootInfo != null) {


      collectMoney(mNodeInfo);//点击收钱

// settingMoney(mNodeInfo);//点击设置金额
// setMoney(mNodeInfo,”0.01”);//输入金额
// addReceiptCause(mNodeInfo);//点击添加收款理由
// setCauser(mNodeInfo,”钱太多WJ”);//设置理由
// clickCommit(mNodeInfo);//点击确定按钮
// savePhoto(mNodeInfo);//保存图片
// rePhotoCode();//解析二维码
bank(mNodeInfo);//返回按钮

        }
    }
    catch (Exception e) {
    }
}

@Override
public void onInterrupt() {
    Log.e("-onInterrupt-","onInterrupt");
}

@Override
public boolean onUnbind(Intent intent) {
    Log.e("-onUnbind-","onUnbind");
    return super.onUnbind(intent);
}

/**
 * 点击收款
 *
 * @param mNodeInfo
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void collectMoney(AccessibilityNodeInfo mNodeInfo) {

    List<AccessibilityNodeInfo> infos = mNodeInfo.findAccessibilityNodeInfosByViewId("xx.xx.xx");

// Log.e(“===点击收款===”, infos.size() + “”);
// rootInfo.recycle();
for (AccessibilityNodeInfo item : infos) {
if (state1){
item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
state1=false;
}
}
}

/**
 * 点击设置金额
 *
 * @param mNodeInfo
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void settingMoney(AccessibilityNodeInfo mNodeInfo) {

        List<AccessibilityNodeInfo> infos = mNodeInfo.findAccessibilityNodeInfosByViewId("xx.xx.xx");

// Log.e(“===点击设置金额===”, infos.size() + “”);
// rootInfo.recycle();

        for (AccessibilityNodeInfo item : infos) {
            if (state2){
            item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                state2=false;
        }
    }

}

/**
 * 点击添加收款理由
 *
 * @param mNodeInfo
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void addReceiptCause(AccessibilityNodeInfo mNodeInfo) {
    List<AccessibilityNodeInfo> infos = mNodeInfo.findAccessibilityNodeInfosByViewId("xx.xx.xx");

// Log.e(“===点击添加收款理由===”, infos.size() + “”);
// rootInfo.recycle();
for (AccessibilityNodeInfo item : infos) {
if (state3){
item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
state3=false;
}
}
}

/**
 * 点击确点按钮
 *
 * @param mNodeInfo
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void clickCommit(AccessibilityNodeInfo mNodeInfo) {//
    List<AccessibilityNodeInfo> infos = mNodeInfo.findAccessibilityNodeInfosByViewId("xx.xx.xx");

// Log.e(“===点击确点按钮===”, infos.size() + “”);
// rootInfo.recycle();
for (AccessibilityNodeInfo item : infos) {
if (state4){
item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
state4=false;
}
}
}

/**
 * 点击保存图片
 *
 * @param mNodeInfo
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void savePhoto(AccessibilityNodeInfo mNodeInfo) {
    List<AccessibilityNodeInfo> infos = mNodeInfo.findAccessibilityNodeInfosByViewId("xx.xx.xx");

// Log.e(“===点击保存图片===”, infos.size() + “”);
// rootInfo.recycle();
for (AccessibilityNodeInfo item : infos) {
if (state5){
timePhoto = (System.currentTimeMillis()+””).substring(0,10);
Log.e(“当前的时间戳截取后=”,timePhoto);//1540470311571
Log.e(“当前的时间戳跳转前=”,System.currentTimeMillis()+””);
item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
Log.e(“当前的时间戳跳转后=”,System.currentTimeMillis()+””);
state5=false;
}
}
}

/**
 * 点击收款记录
 *
 * @param mNodeInfo
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void record(AccessibilityNodeInfo mNodeInfo) {
    List<AccessibilityNodeInfo> infos = mNodeInfo.findAccessibilityNodeInfosByViewId("xx.xx.xx");

// Log.e(“===点击收款记录===”, infos.size() + “”);
// rootInfo.recycle();
for (AccessibilityNodeInfo item : infos) {
if (state6){
item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
state6=false;
}
}
}
/**

 * 点击返回
 *
 * @param mNodeInfo
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void bank(AccessibilityNodeInfo mNodeInfo) {
    List<AccessibilityNodeInfo> infos = mNodeInfo.findAccessibilityNodeInfosByViewId("xx.xx.xx");

    Log.e("===点击返回===", infos.size() + "");

// rootInfo.recycle();
for (final AccessibilityNodeInfo item : infos) {
if (state7<2){
state7++;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
}, 4000);//3秒后执行Runnable中的run方法

        }
    }
}
/**
 * 设置金额
 *
 * @param mNodeInfo
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void setMoney(AccessibilityNodeInfo mNodeInfo,String money) {//

// Log.e(“===写入金额===”, “**”);
final List list = mNodeInfo.findAccessibilityNodeInfosByViewId(“xx.xx.xx”);
if (list != null && !list.isEmpty()) {
AccessibilityNodeInfo info = list.get(0);

        //粘贴板
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("label", money);
        clipboard.setPrimaryClip(clip);

        CharSequence txt = info.getText();
        if (txt == null) txt = "";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Bundle arguments = new Bundle();
            arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, 0);
            arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, txt.length());
            info.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
            info.performAction(AccessibilityNodeInfo.ACTION_SET_SELECTION, arguments);
            info.performAction(AccessibilityNodeInfo.ACTION_PASTE);
        }

    }
}

/**
 * 设置理由
 *
 * @param mNodeInfo
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void setCauser(AccessibilityNodeInfo mNodeInfo,String str) {

// Log.e(“===写入理由===”, “**”);
final List list = mNodeInfo.findAccessibilityNodeInfosByViewId(“xx.xx.xx”);
if (list != null && !list.isEmpty()) {
AccessibilityNodeInfo info = list.get(1);

        //粘贴板
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("label", str);
        clipboard.setPrimaryClip(clip);

        CharSequence txt = info.getText();
        if (txt == null) txt = "";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Bundle arguments = new Bundle();
            arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, 0);
            arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, txt.length());
            info.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
            info.performAction(AccessibilityNodeInfo.ACTION_SET_SELECTION, arguments);
            info.performAction(AccessibilityNodeInfo.ACTION_PASTE);
        }

    }
}



/**
 * 解析二维码
 */
private void rePhotoCode(){
    file_ = new File(Environment.getExternalStorageDirectory()+"/DCIM"+"/Camera/");
    File[] files = file_.listFiles();
    if (files != null) {
        int count = files.length;
        if(count>0){
        for (int i = 0; i < count; i++) {
            File file = files[i];
            if (i==count-1){
                photoString = QRCodeDecoder.syncDecodeQRCode(file.getAbsolutePath());
                Log.e("解析到的图片内容为=", photoString);
                file.delete(); // 删除所有文件
            }

        }
        }
    }
}




/**
 * 滑动
 * 滑动比例 0~20
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void slideVertical() {
    int screenHeight = ScreenUtils.getScreenHeight(getApplicationContext());
    int screenWidth = ScreenUtils.getScreenWidth(getApplicationContext());
    Log.e("屏幕:" + (screenHeight - (screenHeight / 10)) + "/" +
            (screenHeight - (screenHeight - (screenHeight / 10))) + "/" + screenWidth / 2,"");

    Path path = new Path();
    int start = (screenHeight / 20) * 1;
    int stop = (screenHeight / 20) * 2;
    path.moveTo(screenWidth / 2, start);//如果只是设置moveTo就是点击
    path.lineTo(screenWidth / 2, stop);//如果设置这句就是滑动
    GestureDescription.Builder builder = new GestureDescription.Builder();
    GestureDescription gestureDescription = builder
            .addStroke(new GestureDescription.
                    StrokeDescription(path,
                    200,
                    200))
            .build();

    dispatchGesture(gestureDescription, new GestureResultCallback() {
        @Override
        public void onCompleted(GestureDescription gestureDescription) {
            super.onCompleted(gestureDescription);
            Log.e("滑动结束","" + gestureDescription.getStrokeCount());

// next(next, nextTime);
}

        @Override
        public void onCancelled(GestureDescription gestureDescription) {
            super.onCancelled(gestureDescription);
            Log.e("滑动取消","");
        }
    }, null);
}

}

2:配置服务

<service
    android:name="xx.xx.xx.service.AutoClickService"
    android:exported="false"
    android:label="OTCPay"
    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/accessible_service_config" />
</service>

3: @xml/accessible_service_config 文件内容

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagReportViewIds"
android:canRetrieveWindowContent="true"
android:notificationTimeout="0"
android:description="@string/description"    //名字随便起     
android:packageNames="com.xx.xx.xx" //想要点击的应用包名
/>

4: //跳转系统打开自己app名字的无障碍开关
Intent intent2 = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
startActivity(intent2);


作者:杰骜不驯丶
版权声明:本文为博主原创文章,转载请附上博文链接!