Commit 26dd3e83 by zhengli

improved click workflow

parent 9dc3c589
......@@ -2,13 +2,21 @@ package android.app;
import android.content.ContentProviderNative;
import android.content.IContentProvider;
import android.content.Intent;
import android.content.pm.ProviderInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;
import android.os.RemoteException;
public interface IActivityManager {
public int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags,
ProfilerInfo profilerInfo, Bundle options, int userId) throws RemoteException;
public ContentProviderHolder getContentProviderExternal(String name, int userId, IBinder token) throws RemoteException;
public void removeContentProviderExternal(String name, IBinder token) throws RemoteException;
......
package android.app;
public interface IApplicationThread {
}
package android.app;
public class ProfilerInfo {
}
package com.xf.agent;
import android.app.ActivityManagerNative;
import android.app.ActivityThread;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.UserHandle;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityManager;
import com.xf.agent.common.CallRequest;
......@@ -22,6 +26,7 @@ import com.xf.agent.common.server.FLog;
import com.xf.agent.common.server.OpsDataTransfer;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
......@@ -102,9 +107,19 @@ class AgentHandler implements OpsDataTransfer.OnRecvCallback{
TypeCmd typeCmd = ParcelableUtil.unmarshall(callRequest.data, TypeCmd.CREATOR);
if(shell.isClose()){
shell=Shell.getShell();
shell = Shell.getShell();
}
Result execResult = null;
try{
execResult = shell.exec(typeCmd.command);
}catch (Throwable e){
if(e instanceof IllegalStateException){
shell = Shell.getShell();
}
e.printStackTrace();
}
Result execResult = shell.exec(typeCmd.command);
FLog.log(execResult.toString());
......@@ -130,6 +145,29 @@ class AgentHandler implements OpsDataTransfer.OnRecvCallback{
MethodUtils.invokeExactMethod(service,"setDataEnabled",true);
FLog.log("---restart network success --- ");
}else if(callRequest.type == Types.START_ACTIVITY){
Intent intent = ParcelableUtil.unmarshall(callRequest.data, Intent.CREATOR);
getContext().startActivity(intent);
ActivityManagerNative.getDefault().startActivityAsUser(null, null, intent, null,
null, null, 0, 0, null, null, 0);
}else if(callRequest.type == Types.INPUT_EVENT){
String args = new String(callRequest.data);
String[] split = args.trim().split("\\s+");
for (int i = 0; i < split.length; i++) {
split[i] = split[i].trim();
}
FLog.log("input --> "+ Arrays.toString(split));
new Input().run(split);
}else {
System.out.println("unknown type !");
}
......
package com.xf.agent;
import android.hardware.input.InputManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.MotionEvent;
import com.xf.agent.common.MethodUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
/**
* Command that sends key events to the device, either by their keycode, or by
* desired character output.
*/ class Input {
private static final String TAG = "Input";
private static final String INVALID_ARGUMENTS = "Error: Invalid arguments for command: ";
private static final Map<String, Integer> SOURCES = new HashMap<String, Integer>() {{
put("keyboard", InputDevice.SOURCE_KEYBOARD);
put("dpad", InputDevice.SOURCE_DPAD);
put("gamepad", InputDevice.SOURCE_GAMEPAD);
put("touchscreen", InputDevice.SOURCE_TOUCHSCREEN);
put("mouse", InputDevice.SOURCE_MOUSE);
put("stylus", InputDevice.SOURCE_STYLUS);
put("trackball", InputDevice.SOURCE_TRACKBALL);
put("touchpad", InputDevice.SOURCE_TOUCHPAD);
put("touchnavigation", InputDevice.SOURCE_TOUCH_NAVIGATION);
put("joystick", InputDevice.SOURCE_JOYSTICK);
}};
/**
* Command-line entry point.
*
* @param args The command-line arguments
*/
void run(String[] args) {
if (args.length < 1) {
showUsage();
return;
}
int index = 0;
String command = args[index];
int inputSource = InputDevice.SOURCE_UNKNOWN;
if (SOURCES.containsKey(command)) {
inputSource = SOURCES.get(command);
index++;
command = args[index];
}
final int length = args.length - index;
try {
if (command.equals("text")) {
if (length == 2) {
inputSource = getSource(inputSource, InputDevice.SOURCE_KEYBOARD);
sendText(inputSource, args[index+1]);
return;
}
} else if (command.equals("keyevent")) {
if (length >= 2) {
final boolean longpress = "--longpress".equals(args[index + 1]);
final int start = longpress ? index + 2 : index + 1;
inputSource = getSource(inputSource, InputDevice.SOURCE_KEYBOARD);
if (length > start) {
for (int i = start; i < length; i++) {
int keyCode = KeyEvent.keyCodeFromString(args[i]);
if (keyCode == KeyEvent.KEYCODE_UNKNOWN) {
keyCode = KeyEvent.keyCodeFromString("KEYCODE_" + args[i]);
}
sendKeyEvent(inputSource, keyCode, longpress);
}
return;
}
}
} else if (command.equals("tap")) {
if (length == 3) {
inputSource = getSource(inputSource, InputDevice.SOURCE_TOUCHSCREEN);
sendTap(inputSource, Float.parseFloat(args[index+1]),
Float.parseFloat(args[index+2]));
return;
}
} else if (command.equals("swipe")) {
int duration = -1;
inputSource = getSource(inputSource, InputDevice.SOURCE_TOUCHSCREEN);
switch (length) {
case 6:
duration = Integer.parseInt(args[index+5]);
case 5:
sendSwipe(inputSource,
Float.parseFloat(args[index+1]), Float.parseFloat(args[index+2]),
Float.parseFloat(args[index+3]), Float.parseFloat(args[index+4]),
duration);
return;
}
} else if (command.equals("press")) {
inputSource = getSource(inputSource, InputDevice.SOURCE_TRACKBALL);
if (length == 1) {
sendTap(inputSource, 0.0f, 0.0f);
return;
}
} else if (command.equals("roll")) {
inputSource = getSource(inputSource, InputDevice.SOURCE_TRACKBALL);
if (length == 3) {
sendMove(inputSource, Float.parseFloat(args[index+1]),
Float.parseFloat(args[index+2]));
return;
}
} else {
System.err.println("Error: Unknown command: " + command);
showUsage();
return;
}
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
System.err.println(INVALID_ARGUMENTS + command);
showUsage();
}
/**
* Convert the characters of string text into key event's and send to
* device.
*
* @param text is a string of characters you want to input to the device.
*/
private void sendText(int source, String text) {
StringBuffer buff = new StringBuffer(text);
boolean escapeFlag = false;
for (int i=0; i<buff.length(); i++) {
if (escapeFlag) {
escapeFlag = false;
if (buff.charAt(i) == 's') {
buff.setCharAt(i, ' ');
buff.deleteCharAt(--i);
}
}
if (buff.charAt(i) == '%') {
escapeFlag = true;
}
}
char[] chars = buff.toString().toCharArray();
KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
KeyEvent[] events = kcm.getEvents(chars);
for(int i = 0; i < events.length; i++) {
KeyEvent e = events[i];
if (source != e.getSource()) {
e.setSource(source);
}
injectKeyEvent(e);
}
}
private void sendKeyEvent(int inputSource, int keyCode, boolean longpress) {
long now = SystemClock.uptimeMillis();
injectKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyCode, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, inputSource));
if (longpress) {
injectKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyCode, 1, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_LONG_PRESS,
inputSource));
}
injectKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_UP, keyCode, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, inputSource));
}
private void sendTap(int inputSource, float x, float y) {
long now = SystemClock.uptimeMillis();
injectMotionEvent(inputSource, MotionEvent.ACTION_DOWN, now, x, y, 1.0f);
injectMotionEvent(inputSource, MotionEvent.ACTION_UP, now, x, y, 0.0f);
}
private void sendSwipe(int inputSource, float x1, float y1, float x2, float y2, int duration) {
if (duration < 0) {
duration = 300;
}
long now = SystemClock.uptimeMillis();
injectMotionEvent(inputSource, MotionEvent.ACTION_DOWN, now, x1, y1, 1.0f);
long startTime = now;
long endTime = startTime + duration;
while (now < endTime) {
long elapsedTime = now - startTime;
float alpha = (float) elapsedTime / duration;
injectMotionEvent(inputSource, MotionEvent.ACTION_MOVE, now, lerp(x1, x2, alpha),
lerp(y1, y2, alpha), 1.0f);
now = SystemClock.uptimeMillis();
}
injectMotionEvent(inputSource, MotionEvent.ACTION_UP, now, x2, y2, 0.0f);
}
/**
* Sends a simple zero-pressure move event.
*
* @param inputSource the InputDevice.SOURCE_* sending the input event
* @param dx change in x coordinate due to move
* @param dy change in y coordinate due to move
*/
private void sendMove(int inputSource, float dx, float dy) {
long now = SystemClock.uptimeMillis();
injectMotionEvent(inputSource, MotionEvent.ACTION_MOVE, now, dx, dy, 0.0f);
}
private void injectKeyEvent(KeyEvent event) {
Log.i(TAG, "injectKeyEvent: " + event);
// InputManager.getInstance().injectInputEvent(event,
// InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
try {
Object instance = MethodUtils
.invokeStaticMethod(InputManager.class, "getInstance", null);
MethodUtils.invokeExactMethod(instance,"injectInputEvent",new Object[]{event,0},new Class[]{
InputEvent.class,int.class});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Builds a MotionEvent and injects it into the event stream.
*
* @param inputSource the InputDevice.SOURCE_* sending the input event
* @param action the MotionEvent.ACTION_* for the event
* @param when the value of SystemClock.uptimeMillis() at which the event happened
* @param x x coordinate of event
* @param y y coordinate of event
* @param pressure pressure of event
*/
private void injectMotionEvent(int inputSource, int action, long when, float x, float y, float pressure) {
final float DEFAULT_SIZE = 1.0f;
final int DEFAULT_META_STATE = 0;
final float DEFAULT_PRECISION_X = 1.0f;
final float DEFAULT_PRECISION_Y = 1.0f;
final int DEFAULT_DEVICE_ID = 0;
final int DEFAULT_EDGE_FLAGS = 0;
MotionEvent event = MotionEvent.obtain(when, when, action, x, y, pressure, DEFAULT_SIZE,
DEFAULT_META_STATE, DEFAULT_PRECISION_X, DEFAULT_PRECISION_Y, DEFAULT_DEVICE_ID,
DEFAULT_EDGE_FLAGS);
event.setSource(inputSource);
Log.i(TAG, "injectMotionEvent: " + event);
try {
Object instance = MethodUtils
.invokeStaticMethod(InputManager.class, "getInstance", null);
MethodUtils.invokeExactMethod(instance,"injectInputEvent",new Object[]{event,2},new Class[]{
InputEvent.class,int.class});
} catch (Exception e) {
e.printStackTrace();
}
// InputManager.getInstance().injectInputEvent(event,
// InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
}
private static final float lerp(float a, float b, float alpha) {
return (b - a) * alpha + a;
}
private static final int getSource(int inputSource, int defaultSource) {
return inputSource == InputDevice.SOURCE_UNKNOWN ? defaultSource : inputSource;
}
private void showUsage() {
System.err.println("Usage: input [<source>] <command> [<arg>...]");
System.err.println();
System.err.println("The sources are: ");
for (String src : SOURCES.keySet()) {
System.err.println(" " + src);
}
System.err.println();
System.err.println("The commands and default sources are:");
System.err.println(" text <string> (Default: touchscreen)");
System.err.println(" keyevent [--longpress] <key code number or name> ..."
+ " (Default: keyboard)");
System.err.println(" tap <x> <y> (Default: touchscreen)");
System.err.println(" swipe <x1> <y1> <x2> <y2> [duration(ms)]"
+ " (Default: touchscreen)");
System.err.println(" press (Default: trackball)");
System.err.println(" roll <dx> <dy> (Default: trackball)");
}
}
\ No newline at end of file
......@@ -40,6 +40,7 @@ public class Shell {
}
}else {
if(sShell.isClose()){
sShell = null;
try {
sShell = new Shell("sh");
} catch (IOException e) {
......@@ -276,6 +277,7 @@ public class Shell {
if (close) {
throw new IllegalStateException("Unable to add commands to a closed shell");
}
command.setId(generateCommandID());
commandQueue.offer(command);
return command;
......
......@@ -23,4 +23,13 @@ public final class Types {
*/
public static final int RESTART_NETWORK = 4;
/**
* 启动activity
*/
public static final int START_ACTIVITY = 5;
/**
* 事件
*/
public static final int INPUT_EVENT = 6;
}
package com.xf.agent.common.req;
import android.content.Intent;
import com.xf.agent.common.IReq;
import com.xf.agent.common.ParcelableUtil;
import com.xf.agent.common.Types;
public class ReqFactory {
public static IReq startActivity(final Intent intent){
return new IReq() {
@Override
public int getType() {
return Types.START_ACTIVITY;
}
@Override
public byte[] getData() {
return ParcelableUtil.marshall(intent);
}
};
}
public static IReq inputEvent(final String event){
return new IReq() {
@Override
public int getType() {
return Types.INPUT_EVENT;
}
@Override
public byte[] getData() {
return event.getBytes();
}
};
}
}
package com.xf.agent.wrap;
import android.content.Context;
import android.content.Intent;
import com.xf.agent.common.CallResult;
import com.xf.agent.common.CmdResult;
import com.xf.agent.common.NormalCmd;
import com.xf.agent.common.ParcelableUtil;
import com.xf.agent.common.TypeCmd;
import com.xf.agent.common.Types;
import com.xf.agent.common.req.ReqFactory;
public class AgentManager {
......@@ -51,6 +53,23 @@ public class AgentManager {
return true;
}
public boolean startActivity(Intent intent) throws Throwable {
checkConnect();
CallResult result = mLocalServerManager.execNew(ReqFactory.startActivity(intent));
if(result!= null && result.throwable != null){
throw result.throwable;
}
return true;
}
public boolean input(String inputEvent) throws Throwable {
checkConnect();
CallResult result = mLocalServerManager.execNew(ReqFactory.inputEvent(inputEvent));
if(result!= null && result.throwable != null){
throw result.throwable;
}
return true;
}
public void destory() {
if (mLocalServerManager != null) {
......
......@@ -22,8 +22,8 @@ android {
applicationId versions.applicationId
minSdkVersion versions.minSdkVersion
targetSdkVersion versions.targetSdkVersion
versionCode 9
versionName "1.5.7"
versionCode 10
versionName "1.5.8"
multiDexEnabled true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
// externalNativeBuild {
......@@ -85,26 +85,27 @@ dependencies {
implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.github.bumptech.glide:glide:3.5.2'
implementation 'org.greenrobot:eventbus:3.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation "com.android.support:appcompat-v7:$versions.supportLibVersion"
implementation "com.android.support:design:$versions.supportLibVersion"
implementation "com.android.support:recyclerview-v7:${versions.supportLibVersion}"
implementation "com.jakewharton:butterknife:${versions.butterknife}"
annotationProcessor "com.jakewharton:butterknife-compiler:${versions.butterknife}"
implementation 'com.jakewharton:butterknife:8.2.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.2.1'
// implementation 'com.aliyun.ams:alicloud-android-push:3.1.2@aar'
// implementation 'com.aliyun.ams:alicloud-android-utdid:1.1.5.3'
// implementation 'com.aliyun.ams:alicloud-android-ut:5.1.0'
// implementation 'com.aliyun.ams:alicloud-android-third-push:3.0.3@aar'
implementation 'com.aliyun.ams:alicloud-android-push:3.0.11@aar'
implementation 'com.aliyun.ams:alicloud-android-utdid:1.1.5.3'
implementation 'com.aliyun.ams:alicloud-android-ut:5.0.0'
implementation 'com.aliyun.ams:alicloud-android-third-push:3.0.3@aar'
implementation 'com.aliyun.ams:alicloud-android-push:3.1.2'
annotationProcessor "org.androidannotations:androidannotations:$AAVersion"
//annotationProcessor "org.androidannotations:androidannotations:$AAVersion"
annotationProcessor ("com.tinkerpatch.tinker:tinker-android-anno:1.9.2")
implementation("com.tinkerpatch.sdk:tinkerpatch-android-sdk:1.2.2")
annotationProcessor ("com.tinkerpatch.tinker:tinker-android-anno:1.9.6")
implementation("com.tinkerpatch.sdk:tinkerpatch-android-sdk:1.2.6")
implementation "com.android.support:multidex:1.0.3"
}
......
package com.xf.weixinclick;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
......@@ -9,12 +11,15 @@ import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import com.xf.agent.common.CmdResult;
import com.xf.weixinclick.agent.AgentExecutor;
import com.xf.weixinclick.agent.AutoProcesser;
import com.xf.weixinclick.debugtool.LogcatTools;
import com.xf.weixinclick.http.HttpClientApi;
import java.util.concurrent.Callable;
import rx.Single;
import rx.SingleSubscriber;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
......@@ -80,6 +85,85 @@ public class DebugActivity extends BaseActivity {
}
@OnClick(R.id.btn_start_act)
void onClickStartAct(View view){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName("com.tencent.mm","com.tencent.mm.plugin.webview.ui.tools.WebViewUI");
intent.setData(Uri.parse("https://www.baidu.com"));
// AgentExecutor.startActivity(intent).subscribe(new SingleSubscriber<Boolean>() {
// @Override
// public void onSuccess(Boolean aBoolean) {
// Toast.makeText(getApplicationContext(),"启动成功 "+aBoolean,Toast.LENGTH_SHORT).show();
// }
//
// @Override
// public void onError(Throwable error) {
// Log.e(TAG, "onError --> ",error);
// }
// });
String url = "http://test.mp-watch.checheng.net/qr-addr?url=http%253A%252F%252Ftest.mp-watch.checheng.net%252Ftemp%252Fspider%252Fgh_4e07defd60d4%252Flogin_qrcode.png?1522133567961?1522722411902?1526285925734";
AgentExecutor.startWechatWeb(url).subscribe(new SingleSubscriber<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
Log.e(TAG, "onSuccess --> "+aBoolean);
}
@Override
public void onError(Throwable error) {
Log.e(TAG, "onError --> ",error);
}
});
// AgentExecutor.exec("am start -n com.tencent.mm/com.tencent.mm.plugin.webview.ui.tools.WebViewUI -a android.intent.action.VIEW -d https://www.baidu.com")
// .subscribe(new SingleSubscriber<CmdResult>() {
// @Override
// public void onSuccess(CmdResult cmdResult) {
// Log.e(TAG, "onSuccess --> "+cmdResult);
// }
//
// @Override
// public void onError(Throwable error) {
// Log.e(TAG, "onError --> ",error);
// }
// });
}
@OnClick(R.id.btn_test_qr)
void btn_test_qr(View view){
HttpClientApi.getQr(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "onError --> ",e);
}
@Override
public void onNext(String s) {
Log.e(TAG, "onNext --> "+s);
Toast.makeText(getApplicationContext(),"获取成功,请稍等...",Toast.LENGTH_SHORT).show();
}
});
}
private void updateStatus(){
if(LogcatTools.isRunning()){
......
......@@ -95,7 +95,7 @@ public class LoginActivity extends BaseActivity {
new HttpSubscriber<String>() {
@Override
public void onStart() {
execShellCmd("input tap " + 10 + " " + 10);
//execShellCmd("input tap " + 10 + " " + 10);
showProgress("正在请求");
}
......
......@@ -47,6 +47,7 @@ import com.xf.weixinclick.http.HttpClientApi;
import com.xf.weixinclick.http.HttpSubscriber;
import com.xf.weixinclick.receiver.WeChatStatus;
import com.xf.weixinclick.utils.Accessibilitys;
import com.xf.weixinclick.utils.JsonKit;
import com.xf.weixinclick.utils.SP;
import com.xf.weixinclick.view.WaveHelper;
import com.xf.weixinclick.view.WaveView;
......@@ -186,7 +187,7 @@ public class MainActivity extends BaseActivity {
msg.setQr_addr("http://test.mp-watch.checheng.net/qr-addr?url=http%253A%252F%252Ftest.mp-watch.checheng.net%252Ftemp%252Fspider%252Fgh_4e07defd60d4%252Flogin_qrcode.png?1522133567961?1522722411902");
// msg.setQr_addr("https://weapp-dev.wangjia.com/qr.jpg?dd=1");
msg.setUnique_id("1111111111111");
msg.setTime_config(new Gson().fromJson("{\"qrcode_timeout\":60,\"after_open_weixin_index_delay\":2000,\"after_open_weixin_file_helper_delay\":6000,\"after_paste_message_delay\":2000,\"after_send_message_delay\":2000,\"after_click_message_delay\":5000,\"long_press_qrcode_delay\":4000,\"after_click_decode_button_delay\":5000,\"after_click_confirm_button_delay\":3000}", DelayBean.class));
msg.setTime_config(JsonKit.GSON.fromJson("{\"qrcode_timeout\":60,\"after_open_weixin_index_delay\":2000,\"after_open_weixin_file_helper_delay\":6000,\"after_paste_message_delay\":2000,\"after_send_message_delay\":2000,\"after_click_message_delay\":5000,\"long_press_qrcode_delay\":4000,\"after_click_decode_button_delay\":5000,\"after_click_confirm_button_delay\":3000}", DelayBean.class));
//EventBus.getDefault().post(msg);
MsgSender.checkAndSend(getApplicationContext(),msg);
// startWorkService(MainActivity.this,msg);
......@@ -315,7 +316,7 @@ public class MainActivity extends BaseActivity {
// SP.setParam("divice", d_name);
Log.d("fei",responseBase);
Type type = new TypeToken<ResponseBase<EnableResult>>(){}.getType();
ResponseBase<EnableResult> result = new Gson().fromJson(responseBase,type);
ResponseBase<EnableResult> result = JsonKit.GSON.fromJson(responseBase,type);
if (result == null){
NewService.showToast(MainActivity.this,"失败:解析失败");
}else {
......
......@@ -20,6 +20,7 @@ import android.widget.Toast;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.xf.weixinclick.bean.DelayBean;
import com.xf.weixinclick.bean.msg.ReceiverMsg;
import com.xf.weixinclick.core.Worker;
import com.xf.weixinclick.core.Worker2;
import com.xf.weixinclick.http.HttpClientApi;
import com.xf.weixinclick.http.HttpSubscriber;
......@@ -69,12 +70,12 @@ public class NewService extends AccessibilityService {
*/
private boolean inBacking = false;
Worker2 mWorker = null;
Worker mWorker = null;
@Override
public void onCreate() {
super.onCreate();
if (mWorker == null){
mWorker = Worker2.getInstance();
mWorker = Worker.getInstance();
}
Log.d(TAG,"NewService onCreate");
}
......@@ -82,19 +83,22 @@ public class NewService extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.d(TAG, "NewService onAccessibilityEvent");
if (mWorker == null){
mWorker = Worker2.getInstance();
mWorker = Worker.getInstance();
}
mWorker.onAccessibilityEvent(getRootInActiveWindow(),event);
//mWorker.onAccessibilityEvent(getRootInActiveWindow(),event);
mWorker.handleEvent(this,event);
}
@Override
public void onInterrupt () {
Log.d(TAG, "NewService onInterrupt");
if (mWorker != null){
mWorker.onIntercept();
//mWorker.onIntercept();
mWorker.onInterrupt(this);
}
}
......@@ -291,7 +295,6 @@ public class NewService extends AccessibilityService {
if (TextUtils.isEmpty(name)){
return;
}
String device_code = PushServiceFactory.getCloudPushService().getDeviceId();
if (TextUtils.isEmpty(device_code)){
return;
......
package com.xf.weixinclick.agent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.Log;
......@@ -84,6 +85,42 @@ public class AgentExecutor {
}
public static Single<Boolean> inputEvent(final String event){
return Single.fromCallable(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
return agentManager.input(event);
} catch (Throwable throwable) {
throw new Exception(throwable);
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
public static Single<Boolean> startWechatWeb(final String url){
return Single.fromCallable(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
String cmd = "am start -n com.tencent.mm/com.tencent.mm.plugin.webview.ui.tools.WebViewUI -a android.intent.action.VIEW -d ";
return agentManager.exeCommand(cmd+url).code == 0;
} catch (Throwable throwable) {
throw new Exception(throwable);
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
public static boolean isConnected(){
return agentManager.isRunning();
......
......@@ -45,9 +45,7 @@ public class AutoProcesser {
@Override
public void onError(Throwable error) {
DebugTools.dismiss();
Cmder.clickWxBack();
Cmder.clickWxBack();
Cmder.clickWxBack();
Log.e(TAG, "onError --> ",error);
if(subscriber != null){
......
......@@ -2,9 +2,11 @@ package com.xf.weixinclick.agent;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat.FocusRealDirection;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import com.xf.agent.common.CmdResult;
import rx.SingleSubscriber;
/**
......@@ -12,9 +14,10 @@ import com.xf.agent.common.CmdResult;
*/
public class MotionRunner {
private static final String KEY_EVENT_CMD = "input keyevent ";
private static final String TAP_EVENT_CMD = "input tap ";
private static final String SWIPE_EVENT_CMD = "input swipe ";
private static final String PREFIX = "";
private static final String KEY_EVENT_CMD = PREFIX+" keyevent ";
private static final String TAP_EVENT_CMD = PREFIX+" tap ";
private static final String SWIPE_EVENT_CMD = PREFIX+" swipe ";
private static MotionRunner sInstance = null;
......@@ -64,10 +67,13 @@ public class MotionRunner {
*/
public boolean tap(int x,int y){
CmdResult cmdResult = AgentExecutor.execNonReturn(TAP_EVENT_CMD + x + " " + y);
return cmdResult!=null && cmdResult.code == 0;
// CmdResult cmdResult = AgentExecutor.execNonReturn(TAP_EVENT_CMD + x + " " + y);
//
// return cmdResult!=null && cmdResult.code == 0;
execInputEvent(TAP_EVENT_CMD + x + " " + y);
return true;
//return AgentExecutor.inputEvent(TAP_EVENT_CMD + x + " " + y).toBlocking().value();
}
/**
......@@ -85,7 +91,7 @@ public class MotionRunner {
.append(y).append(' ')
.append(duration);
AgentExecutor.execNonReturn(cmd.toString());
execInputEvent(cmd.toString());
}
/**
......@@ -103,7 +109,7 @@ public class MotionRunner {
.append(endX).append(' ')
.append(endY).append(' ')
.append(duration);
AgentExecutor.execNonReturn(cmd.toString());
execInputEvent(cmd.toString());
}
/**
......@@ -142,8 +148,23 @@ public class MotionRunner {
}
private void sendKeyEvent(int code){
AgentExecutor.execNonReturn(KEY_EVENT_CMD+code);
execInputEvent(KEY_EVENT_CMD+code);
}
private void execInputEvent(String event){
Log.e("MotionRunner", "execInputEvent --> "+event);
AgentExecutor.inputEvent(event).subscribe(new SingleSubscriber<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
}
@Override
public void onError(Throwable error) {
Log.e("test", "onError --> ",error);
}
});
}
}
......@@ -27,14 +27,27 @@ public class UiHierarchyFinder {
private BasicTreeNode basicTreeNode;
public static Single<UiHierarchyFinder> createFinder(){
return Single.fromCallable(new Callable<UiHierarchyFinder>() {
@Override
public UiHierarchyFinder call() throws Exception {
UiHierarchyFinder finder = new UiHierarchyFinder();
finder.dump();
finder.parseDefault();
return finder;
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
public void dump() {
// CmdResult value = AgentExecutor.exec(CMD).toBlocking().value();
boolean success = Cmder.execShellCmd(CMD);
Log.e(TAG, "dump --> "+success);
CmdResult value = AgentExecutor.exec(CMD).toBlocking().value();
// boolean success = Cmder.execShellCmd(CMD);
Log.e(TAG, "dump --> "+value.message);
SystemClock.sleep(2000);
if(!success){
if(value.code != 0){
throw new RuntimeException("dump ERROR !!!");
}
......@@ -91,31 +104,81 @@ public class UiHierarchyFinder {
List<UiNode> findNodeByText(String text) {
List<UiNode> ret = new ArrayList<>();
findByAttr(basicTreeNode.getChildren(), "text", text, ret);
findByAttr(basicTreeNode.getChildren(), "text", text, ret,true);
return ret;
}
public @NonNull
List<UiNode> findNodeByAttr(String attrKey,String text) {
List<UiNode> ret = new ArrayList<>();
findByAttr(basicTreeNode.getChildren(), attrKey, text, ret,false);
return ret;
}
public @NonNull
List<UiNode> findNodeByAttr(String attrKey,String text,boolean exact) {
List<UiNode> ret = new ArrayList<>();
findByAttr(basicTreeNode.getChildren(), attrKey, text, ret,exact);
return ret;
}
public @NonNull
List<UiNode> findNodeById(String id) {
List<UiNode> ret = new ArrayList<>();
findByAttr(basicTreeNode.getChildren(), "resource-id", id, ret);
findByAttr(basicTreeNode.getChildren(), "resource-id", id, ret,true);
return ret;
}
public List<String> getAttrValues(String key){
List<String> ret = new ArrayList<>();
getValue(basicTreeNode.getChildren(),key,ret);
return ret;
}
private void findByAttr(BasicTreeNode[] nodes, String key, String value, List<UiNode> ret) {
private void getValue(BasicTreeNode[] nodes, String key,List<String> ret){
if (nodes != null) {
for (BasicTreeNode node : nodes) {
if (node.hasChild()) {
getValue(node.getChildren(), key, ret);
} else {
if (node instanceof UiNode) {
String text = ((UiNode) node).getAttribute(key);
if(!TextUtils.isEmpty(text) && text.length() > 1){
ret.add(text.trim());
}
}
}
}
}
}
private void findByAttr(BasicTreeNode[] nodes, String key, String value, List<UiNode> ret,boolean exact) {
if (nodes != null) {
for (BasicTreeNode node : nodes) {
if (node.hasChild()) {
findByAttr(node.getChildren(), key, value, ret);
findByAttr(node.getChildren(), key, value, ret,exact);
} else {
if (node instanceof UiNode) {
String text = ((UiNode) node).getAttribute(key);
if (ret != null && TextUtils.equals(text, value)) {
if (ret != null && !TextUtils.isEmpty(text) ) {
if( (exact && TextUtils.equals(text, value)) || text.contains(value)){
ret.add(((UiNode) node));
}
}
}
}
......@@ -130,9 +193,10 @@ public class UiHierarchyFinder {
printNodes(node.getChildren());
} else {
if (node instanceof UiNode) {
String text = ((UiNode) node).getAttribute("text");
if (!TextUtils.isEmpty(text)) {
Log.e(TAG, "printNodes --> " + text);
String text1 = ((UiNode) node).getAttribute("text");
String text2 = ((UiNode) node).getAttribute("content-desc");
if (!TextUtils.isEmpty(text1) || !TextUtils.isEmpty(text2) ) {
Log.e(TAG, "printNodes -->text: " + text1+" content-desc:"+text2);
}
}
}
......
......@@ -66,6 +66,7 @@ public class EnableAccessibility implements Callable<Boolean> {
Log.e(TAG, "点击第0个节点的位置"+bounds);
MotionRunner.get().clickBack();
Cmder.clickPX(bounds.centerX(),bounds.centerY());
SystemClock.sleep(5000);
//打开了无障碍页面
......@@ -122,8 +123,6 @@ public class EnableAccessibility implements Callable<Boolean> {
//然后返回
Cmder.clickWxBack();
SystemClock.sleep(500);
Cmder.clickWxBack();
......
......@@ -2,6 +2,7 @@ package com.xf.weixinclick.bean;
import com.google.gson.Gson;
import com.xf.weixinclick.utils.JsonKit;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
......@@ -32,15 +33,13 @@ public class ResponseBase<T> {
}
public static ResponseBase fromJson(String json, Class clazz) {
Gson gson = new Gson();
Type objectType = type(ResponseBase.class, clazz);
return gson.fromJson(json, objectType);
return JsonKit.GSON.fromJson(json, objectType);
}
public String toJson(Class<T> clazz) {
Gson gson = new Gson();
Type objectType = type(ResponseBase.class, clazz);
return gson.toJson(this, objectType);
return JsonKit.GSON.toJson(this, objectType);
}
static ParameterizedType type(final Class raw, final Type... args) {
......
......@@ -14,8 +14,10 @@ import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import com.xf.weixinclick.NewService;
import android.widget.Toast;
import com.xf.weixinclick.agent.AgentExecutor;
import com.xf.weixinclick.agent.AutoProcesser;
import com.xf.weixinclick.agent.MotionRunner;
import com.xf.weixinclick.agent.UiHierarchyFinder;
......@@ -23,9 +25,8 @@ import com.xf.weixinclick.agent.uiautomator.UiNode;
import com.xf.weixinclick.bean.msg.ReceiverMsg;
import com.xf.weixinclick.myApplication;
import com.xf.weixinclick.utils.Accessibilitys;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.greenrobot.eventbus.EventBus;
import rx.SingleSubscriber;
class TaskSession {
......@@ -54,6 +55,8 @@ class TaskSession {
this.message = message;
context = myApplication.getInstence();
taskCallback = callback;
taskLog("收到消息 "+message.getUnique_id());
handler = new Handler(Looper.getMainLooper(), new Callback() {
@Override
public boolean handleMessage(Message msg) {
......@@ -82,13 +85,13 @@ class TaskSession {
//启动微信
startWechat();
//开始监听事件
step = 0;
}
};
//先检查辅助服务
if(!Accessibilitys.isSettingsOn(context)){
taskLog("辅助服务没有开启,自动打开...");
//没有开启,先打开
AutoProcesser.enableAccessibility(context, new SingleSubscriber<Boolean>() {
@Override
......@@ -99,7 +102,7 @@ class TaskSession {
runnable.run();
}else {
} else {
isEnd = true;
taskLog("auto open AccessibilityService fail?");
......@@ -130,6 +133,33 @@ class TaskSession {
//启动微信
private void startWechat(){
AgentExecutor.startWechatWeb(message.getQr_addr()).subscribe(new SingleSubscriber<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
if(aBoolean){
taskLog("使用root打开qr_addr成功");
setNextStep(51);
trackTimeout("无法识别二维码,或许页面打开错误");
}else {
taskLog("使用root打开url失败,尝试打开文件传输助手");
startWxOld();
}
}
@Override
public void onError(Throwable error) {
taskLog("使用root打开url错误",error);
startWxOld();
}
});
}
private void startWxOld(){
Intent intent = new Intent();
ComponentName cmp = new ComponentName(WX_PKG, WX_MAIN_UI);
intent.setAction(Intent.ACTION_MAIN);
......@@ -137,33 +167,35 @@ class TaskSession {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.setComponent(cmp);
context.startActivity(intent);
setNextStep(0);
}
void handleEvent(AccessibilityService service,AccessibilityEvent event){
void handleEvent(final AccessibilityService service,AccessibilityEvent event){
this.service = service;
if(step == -1 || isEnd){
return;
}
Log.e(TAG, "handleEvent --> "+event);
//Log.e(TAG, "handleEvent --> "+event);
final AccessibilityNodeInfo rootInActiveWindow = service.getRootInActiveWindow();
if(rootInActiveWindow != null){
if(step == 0 ){
//先点击[微信]按钮
AccessibilityNodeInfo homeWX = findByIdAndText(rootInActiveWindow, WXIdsConfig.TV_HOME_WX,
AccessibilityNodeInfo homeWX = UIFinderUtils.findByIdAndText(rootInActiveWindow, WXIdsConfig.TV_HOME_WX,
"微信");
taskLog("查找 homeWX "+homeWX);
if(clickNode(homeWX)){
if(UIFinderUtils.clickNode(homeWX)){
taskLog("点击微信 成功!");
setNextStep(10);
......@@ -174,11 +206,11 @@ class TaskSession {
}else if(step == 10){
//当前在微信首页了
AccessibilityNodeInfo homeWX = findByIdAndText(rootInActiveWindow, WXIdsConfig.HOME_MSG_TITLE,
AccessibilityNodeInfo homeWX = UIFinderUtils.findByIdAndText(rootInActiveWindow, WXIdsConfig.HOME_MSG_TITLE,
"文件传输助手");
taskLog("查找 文件传输助手 "+homeWX);
if(clickNode(homeWX)){
if(UIFinderUtils.clickNode(homeWX)){
taskLog("点击微信 文件传输助手!");
setNextStep(20);
......@@ -191,7 +223,7 @@ class TaskSession {
}else if(step == 20){
//进入聊天界面并填充
AccessibilityNodeInfo changeInput = findByIdAndDesc(rootInActiveWindow,
AccessibilityNodeInfo changeInput = UIFinderUtils.findByIdAndDesc(rootInActiveWindow,
WXIdsConfig.BTN_CHANGE_INPUT, "切换到键盘");
if(changeInput != null){
......@@ -204,7 +236,7 @@ class TaskSession {
}
AccessibilityNodeInfo etNodeInfo = findEditText(rootInActiveWindow);
AccessibilityNodeInfo etNodeInfo = UIFinderUtils.findEditText(rootInActiveWindow);
if(etNodeInfo != null) {
Bundle arguments = new Bundle();
......@@ -228,15 +260,15 @@ class TaskSession {
delayRun(2000, new Runnable() {
@Override
public void run() {
AccessibilityNodeInfo editText = findEditText(rootInActiveWindow);
AccessibilityNodeInfo editText = UIFinderUtils.findEditText(rootInActiveWindow);
if(editText != null){
taskLog("点击输入框");
clickNode(editText);
UIFinderUtils.clickNode(editText);
setNextStep(30);
recycle(rootInActiveWindow);
UIFinderUtils.recycle(rootInActiveWindow);
}else {
taskLog("没有找到输入框!!");
trackTimeout("没有找到输入框,无法切换到线索发送按钮!");
......@@ -259,7 +291,7 @@ class TaskSession {
sendMsg(rootInActiveWindow);
try {
recycle(rootInActiveWindow);
UIFinderUtils.recycle(rootInActiveWindow);
} catch (Exception e) {
e.printStackTrace();
}
......@@ -303,7 +335,7 @@ class TaskSession {
// boolean b = lastMsgNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
// taskLog("点击最后一条消息 "+b);
boolean b = clickNode(lastMsgNode);
boolean b = UIFinderUtils.clickNode(lastMsgNode);
taskLog("点击最后一条消息 "+b);
setNextStep(50);
......@@ -330,7 +362,7 @@ class TaskSession {
//长按
taskLog("长按图片");
delayRun(3000, new Runnable() {
delayRun(message.getTime_config().getAfter_click_message_delay()+2000, new Runnable() {
@Override
public void run() {
taskLog("长按图片识别");
......@@ -343,19 +375,19 @@ class TaskSession {
}else if(step == 53){
//识别图片中的二维码
AccessibilityNodeInfo qrScan = findByIdAndText(rootInActiveWindow,
WXIdsConfig.BTN_SCAN_QR, "识别图中二维码");
String text = "识别图中二维码";
List<AccessibilityNodeInfo> infos = rootInActiveWindow
.findAccessibilityNodeInfosByText(text);
taskLog("搜索 识别图片中的二维码");
if(qrScan != null){
taskLog("点击 识别图片中的二维码");
taskLog("搜索文字 "+text);
if(!isEmptyNodes(infos)){
taskLog("点击 "+text);
clickNode(qrScan);
UIFinderUtils.clickNode(infos.get(0));
isOkStep();
setNextStep(54);
}else {
trackTimeout("找不到 识别图中二维码按钮");
setNextStep(55);
} else {
trackTimeout("找不到 "+text);
}
......@@ -376,55 +408,231 @@ class TaskSession {
step = 56;
delayRun(3000, new Runnable() {
// delayRun(message.getTime_config().getAfter_click_decode_button_delay()+3000, new Runnable() {
// @Override
// public void run() {
//
// UiHierarchyFinder.createFinder().subscribe(new SingleSubscriber<UiHierarchyFinder>() {
// @Override
// public void onSuccess(UiHierarchyFinder finder) {
// //finder.printNodes();
//
// List<String> attrValues = finder.getAttrValues("content-desc");
// attrValues.remove("取消");
// attrValues.remove("返回");
// attrValues.remove("更多");
//
// taskLog("可能的文字 --> "+attrValues);
//
// String[] keys = {"确定","确认","关注","登录"};
//
// boolean clicked = false;
//
// for (String key : keys) {
// List<UiNode> list = finder.findNodeByText(key);
//
// taskLog("搜索"+key+" text-> "+list);
// if(!list.isEmpty()){
// list.get(0).getBounds(nodeRect);
//
// clickOk(nodeRect.centerX(),nodeRect.centerY());
// clicked = true;
// break;
// }else {
//
// list = finder.findNodeByAttr("content-desc",key,true);
// taskLog("搜索"+key+" content-desc-> "+list);
// if(!list.isEmpty()){
// list.get(0).getBounds(nodeRect);
//
// clickOk(nodeRect.centerX(),nodeRect.centerY());
// clicked = true;
// break;
// }
//
// }
// }
//
// if (!clicked){
// clickOk(0,0);
// }
//
// }
//
// @Override
// public void onError(Throwable error) {
// taskLog("搜索确认失败",error);
//
// clickOk(0,0);
// }
// });
//
//
// }
// });
}else if(step == 56){
boolean clicked = false;
String[] keys = {"确定","确认","关注","登录"};
for (final String key : keys) {
final List<AccessibilityNodeInfo> list = UIFinderUtils.findAccessibilityNodeInfosByDesc(rootInActiveWindow,key,true);
if(!isEmptyNodes(list)){
taskLog("搜索到"+key+"按钮个数 -> "+list.size());
delayRun(2000, new Runnable() {
@Override
public void run() {
if(MotionRunner.get().tap(200,680)){
setNextStep(60);
isOkStep();
}else {
trackTimeout("点击确定失败!");
taskLog("点击 "+key +" 按钮");
UIFinderUtils.clickNode(list.get(0));
Toast.makeText(context,"点击了 "+key+"按钮 ",Toast.LENGTH_SHORT).show();
trackTimeout("好像找不到 确认登录 按钮");
}
});
delayRun(4000, new Runnable() {
@Override
public void run() {
String[] args = {"已确认","已关注","已登录"};
for (String arg : args) {
List<AccessibilityNodeInfo> list = UIFinderUtils
.findAccessibilityNodeInfosByDesc(service.getRootInActiveWindow(), arg, false);
if(!isEmptyNodes(list)){
taskLog("找到--> "+arg +" 相关文字,确认成功");
successBack();
break;
}
}
}
});
} else if(step == 60){
setNextStep(57);
clicked = true;
break;
}
}
if(!clicked){
trackTimeout("没有找到 确认 相关按钮!");
}
}else if(step == 60){
//step = 61;
taskLog("搜索是否确认登录");
String[] args = {"已确认","已关注","已登录"};
boolean found = false;
for (String arg : args) {
List<AccessibilityNodeInfo> list = UIFinderUtils
.findAccessibilityNodeInfosByDesc(rootInActiveWindow, arg, false);
if(!isEmptyNodes(list)){
found= true;
taskLog("找到--> "+arg +" 相关文字,确认成功");
successBack();
break;
}
}
if(!found){
trackTimeout("找不到 确认登录 标记,");
}
}
}
UIFinderUtils.recycle(rootInActiveWindow);
}
private void clickOk(int x,int y){
if (x == 0) {
x = 200;
}
if(y == 0){
y = 600;
}
taskLog("点击按钮 x:"+x+" y:"+y);
step = 61;
if(MotionRunner.get().tap(x,y)){
taskLog("run --> 点击了 确定|登录|关注 按钮");
setNextStep(60);
delayRun(3000, new Runnable() {
@Override
public void run() {
UiHierarchyFinder finder = new UiHierarchyFinder();
finder.dumpAndFindByNameAsync("").subscribe(new SingleSubscriber<List<UiNode>>() {
UiHierarchyFinder.createFinder().subscribe(new SingleSubscriber<UiHierarchyFinder>() {
@Override
public void onSuccess(List<UiNode> uiNodes) {
public void onSuccess(UiHierarchyFinder finder) {
List<String> attrValues = finder.getAttrValues("content-desc");
attrValues.remove("取消");
attrValues.remove("返回");
attrValues.remove("更多");
taskLog("可能包含有用的文字 --> "+attrValues);
//finder.printNodes();
List<UiNode> list = finder.findNodeByAttr("content-desc", "已确认");
taskLog("检测是否已确认"+list);
if(!list.isEmpty()){
taskLog("找到[已确认]相关提示,操作成功!");
successBack();
}
}
@Override
public void onError(Throwable error) {
taskLog("onError -->搜索已确认登录文字失败 ",error);
}
});
}
});
boolean isLogined = contains(rootInActiveWindow, "已确认登录");
}else {
trackTimeout("点击确定失败!");
}
}
if(isLogined){
private void successBack(){
isOkStep();
end();
......@@ -432,66 +640,43 @@ class TaskSession {
delayRun(2000, new Runnable() {
@Override
public void run() {
MotionRunner.get().clickBack();
taskLog("成功 返回 1");
clickBack();
}
});
delayRun(4000, new Runnable() {
@Override
public void run() {
MotionRunner.get().clickBack();
taskLog("成功 返回 2");
clickBack();
}
});
delayRun(6000, new Runnable() {
@Override
public void run() {
MotionRunner.get().clickBack();
taskLog("成功 返回 3");
clickBack();
onSuccess();
}
});
}else {
trackTimeout("找不到 确认登录 标记");
}
}
}
recycle(rootInActiveWindow);
}
private void setNextStep(int nextStep){
isOkStep();
step = nextStep;
}
private boolean contains(AccessibilityNodeInfo nodeInfo,String text){
int childCount = nodeInfo.getChildCount();
if (childCount > 0) {
for (int i = 0; i < nodeInfo.getChildCount(); i++) {
AccessibilityNodeInfo child = nodeInfo.getChild(i);
if(child != null){
contains(child,text);
}
}
}else {
CharSequence viewText = nodeInfo.getText();
if(!TextUtils.isEmpty(viewText)){
return viewText.toString().startsWith(text);
}
}
return false;
}
private void sendMsg(AccessibilityNodeInfo rootInActiveWindow) {
AccessibilityNodeInfo btnSend = findByIdAndText(rootInActiveWindow, WXIdsConfig.BTN_SEND_MSG,
AccessibilityNodeInfo btnSend = UIFinderUtils.findByIdAndText(rootInActiveWindow, WXIdsConfig.BTN_SEND_MSG,
"发送");
if(btnSend != null){
......@@ -509,74 +694,16 @@ class TaskSession {
}
private void printNodes(List<AccessibilityNodeInfo> nodes){
if(nodes == null || nodes.isEmpty()){
Log.e(TAG, "printNodes --> is empty!");
}else {
Log.e(TAG, "printNodes --> start");
for (AccessibilityNodeInfo node : nodes) {
Log.e(TAG, "printNodes --> "+node.getViewIdResourceName()+" "+node.getText());
}
Log.e(TAG, "printNodes --> end");
}
}
private AccessibilityNodeInfo findByIdAndText(AccessibilityNodeInfo rootInActiveWindow,String id,String text){
List<AccessibilityNodeInfo> nodeInfos = rootInActiveWindow
.findAccessibilityNodeInfosByViewId(id);
if(isEmptyNodes(nodeInfos)){
return null;
}
for (AccessibilityNodeInfo nodeInfo : nodeInfos) {
if(TextUtils.equals(text,nodeInfo.getText())){
return nodeInfo;
}
}
return null;
}
private AccessibilityNodeInfo findByIdAndDesc(AccessibilityNodeInfo rootInActiveWindow,String id,String text){
List<AccessibilityNodeInfo> nodeInfos = rootInActiveWindow
.findAccessibilityNodeInfosByViewId(id);
if(isEmptyNodes(nodeInfos)){
return null;
}
for (AccessibilityNodeInfo nodeInfo : nodeInfos) {
if(TextUtils.equals(text,nodeInfo.getContentDescription())){
return nodeInfo;
}
}
return null;
}
private boolean isEmptyNodes(List<AccessibilityNodeInfo> nodeInfos){
return nodeInfos == null || nodeInfos.isEmpty();
}
private void recycle(AccessibilityNodeInfo info) {
if (info == null){
return;
}
int childCount = info.getChildCount();
if (childCount > 0) {
for (int i = 0; i < info.getChildCount(); i++) {
recycle(info.getChild(i));
}
}else {
info.recycle();
}
}
private void taskLog(String log){
Log.e(TAG,step+" "+ log+LINE_SEP);
WXLog.log(step+" "+ log);
}
private void taskLog(String log,Throwable throwable){
......@@ -592,54 +719,24 @@ class TaskSession {
handler.postDelayed(runnable,delay);
}
//点击
private boolean clickNode(AccessibilityNodeInfo nodeInfo){
nodeRect.setEmpty();
if(nodeInfo != null){
nodeInfo.getBoundsInScreen(nodeRect);
}
if(nodeRect.isEmpty()){
return false;
}
return MotionRunner.get().tap(nodeRect.centerX(),nodeRect.centerY());
}
private boolean isWechatUI(AccessibilityEvent event){
return event != null && TextUtils.equals(event.getClassName(),WX_MAIN_UI);
}
private void trackTimeout(String timeOutMsg){
taskLog("检查超时---");
if(!isEnd) {
Message msg = Message.obtain();
msg.what = TIME_OUT_WHAT;
msg.obj = timeOutMsg;
handler.removeMessages(TIME_OUT_WHAT);
handler.sendMessageDelayed(msg,1000*20);
handler.sendMessageDelayed(msg, 1000 * 20);
}
}
private void isOkStep(){
handler.removeMessages(TIME_OUT_WHAT);
}
private AccessibilityNodeInfo findEditText(AccessibilityNodeInfo rootInActiveWindow){
List<AccessibilityNodeInfo> ets = rootInActiveWindow
.findAccessibilityNodeInfosByViewId(WXIdsConfig.ET_INPUT_MSG);
if(ets != null && !ets.isEmpty()){
for (AccessibilityNodeInfo et : ets) {
if("android.widget.EditText".equals(et.getClassName())){
return et;
}
}
}
return null;
}
//成功回调
......@@ -650,11 +747,32 @@ class TaskSession {
}
//失败
private void onError(String msg){
private void onError(final String msg){
delayRun(2000, new Runnable() {
@Override
public void run() {
clickBack();
}
});
delayRun(4000, new Runnable() {
@Override
public void run() {
if(step >= 55){
clickBack();
}
end();
taskCallback.onError(msg);
service = null;
}
});
}
//停止接收事件
void end(){
......@@ -666,6 +784,16 @@ class TaskSession {
}
private void clickBack(){
if(service != null && service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)){
}else {
MotionRunner.get().clickBack();
}
}
interface TaskCallback{
......
package com.xf.weixinclick.core;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;
import com.xf.weixinclick.agent.MotionRunner;
import java.util.ArrayList;
import java.util.List;
class UIFinderUtils {
private static final String TAG = "UIFinderUtils";
private static Rect nodeRect = new Rect();
static List<AccessibilityNodeInfo> findAccessibilityNodeInfosByDesc(AccessibilityNodeInfo node,String text,boolean exact){
List<AccessibilityNodeInfo> ret = new ArrayList<>();
findByDesc(node,text,exact,ret);
return ret;
}
private static void findByDesc(AccessibilityNodeInfo info,String text,boolean exact,List<AccessibilityNodeInfo> ret){
if (info == null){
return;
}
int childCount = info.getChildCount();
if (childCount > 0) {
for (int i = 0; i < info.getChildCount(); i++) {
findByDesc(info.getChild(i),text,exact,ret);
}
}else {
CharSequence contentDescription = info.getContentDescription();
if(!TextUtils.isEmpty(contentDescription)){
String s = contentDescription.toString();
s=s.trim();
if(exact){
if(TextUtils.equals(text,s)){
ret.add(info);
}
}else {
if(s.contains(text)){
ret.add(info);
}
}
}
}
}
static AccessibilityNodeInfo findEditText(AccessibilityNodeInfo rootInActiveWindow){
List<AccessibilityNodeInfo> ets = rootInActiveWindow
.findAccessibilityNodeInfosByViewId(WXIdsConfig.ET_INPUT_MSG);
if(ets != null && !ets.isEmpty()){
for (AccessibilityNodeInfo et : ets) {
if("android.widget.EditText".equals(et.getClassName())){
return et;
}
}
}
return null;
}
static boolean contains(AccessibilityNodeInfo nodeInfo,String text){
int childCount = nodeInfo.getChildCount();
if (childCount > 0) {
for (int i = 0; i < nodeInfo.getChildCount(); i++) {
AccessibilityNodeInfo child = nodeInfo.getChild(i);
if(child != null){
return contains(child,text);
}
}
}else {
CharSequence viewText = nodeInfo.getText();
if(!TextUtils.isEmpty(viewText)){
return viewText.toString().startsWith(text);
}
}
return false;
}
static boolean clickNode(AccessibilityNodeInfo nodeInfo){
nodeRect.setEmpty();
if(nodeInfo != null){
nodeInfo.getBoundsInScreen(nodeRect);
}
if(nodeRect.isEmpty()){
return false;
}
AccessibilityNodeInfo clickableNode = null;
while (clickableNode == null){
if(nodeInfo != null){
if(nodeInfo.isClickable()){
clickableNode = nodeInfo;
}else {
nodeInfo = nodeInfo.getParent();
}
}else {
break;
}
}
boolean ret = false;
if (clickableNode != null){
ret = clickableNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
return ret || MotionRunner.get().tap(nodeRect.centerX(),nodeRect.centerY());
}
static AccessibilityNodeInfo findByIdAndText(AccessibilityNodeInfo rootInActiveWindow,String id,String text){
List<AccessibilityNodeInfo> nodeInfos = rootInActiveWindow
.findAccessibilityNodeInfosByViewId(id);
if(isEmptyNodes(nodeInfos)){
return null;
}
for (AccessibilityNodeInfo nodeInfo : nodeInfos) {
if(TextUtils.equals(text,nodeInfo.getText())){
return nodeInfo;
}
}
return null;
}
static void printNodes(List<AccessibilityNodeInfo> nodes){
if(nodes == null || nodes.isEmpty()){
Log.e(TAG, "printNodes --> is empty!");
}else {
Log.e(TAG, "printNodes --> start");
for (AccessibilityNodeInfo node : nodes) {
Log.e(TAG, "printNodes --> "+node.getViewIdResourceName()+" "+node.getText()+" "+node.getContentDescription());
}
Log.e(TAG, "printNodes --> end");
}
}
static AccessibilityNodeInfo findByIdAndDesc(AccessibilityNodeInfo rootInActiveWindow,String id,String text){
List<AccessibilityNodeInfo> nodeInfos = rootInActiveWindow
.findAccessibilityNodeInfosByViewId(id);
if(isEmptyNodes(nodeInfos)){
return null;
}
for (AccessibilityNodeInfo nodeInfo : nodeInfos) {
if(TextUtils.equals(text,nodeInfo.getContentDescription())){
return nodeInfo;
}
}
return null;
}
static void recycle(AccessibilityNodeInfo info) {
if (info == null){
return;
}
int childCount = info.getChildCount();
if (childCount > 0) {
for (int i = 0; i < info.getChildCount(); i++) {
recycle(info.getChild(i));
}
}else {
info.recycle();
}
}
private static boolean isEmptyNodes(List<AccessibilityNodeInfo> nodeInfos){
return nodeInfos == null || nodeInfos.isEmpty();
}
}
package com.xf.weixinclick.core;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.xf.weixinclick.http.HttpClientApi;
import com.xf.weixinclick.utils.SP;
import rx.Subscriber;
class WXLog {
static void log(String msg){
String name = (String) SP.getParam("divice", "");
if (TextUtils.isEmpty(name)){
return;
}
String device_code = PushServiceFactory.getCloudPushService().getDeviceId();
if (TextUtils.isEmpty(device_code)){
return;
}
//不管成功还是失败
HttpClientApi.uploadDeviceLog(device_code,name, msg, new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.d("uploadDeviceLog",e.getMessage());
}
@Override
public void onNext(String o) {
Log.d("uploadDeviceLog",o);
}
});
}
}
......@@ -4,8 +4,10 @@ import android.accessibilityservice.AccessibilityService;
import android.support.annotation.Keep;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;
import com.xf.weixinclick.bean.msg.ReceiverMsg;
import com.xf.weixinclick.core.TaskSession.TaskCallback;
import com.xf.weixinclick.myApplication;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
......@@ -90,7 +92,7 @@ public class Worker {
if (currentTaskSession != null && currentTaskSession.canHandle()) {
currentTaskSession.handleEvent(service, event);
} else {
Log.e(TAG, "handleEvent --> 当前不需要处理"+LINE_SEP);
//Log.e(TAG, "handleEvent --> 当前不需要处理"+LINE_SEP);
}
}
......@@ -136,13 +138,19 @@ public class Worker {
currentTaskSession = new TaskSession(msg, new TaskCallback() {
@Override
public void onSuccess() {
Log.e(TAG, "onSuccess --> "+LINE_SEP);
Toast.makeText(myApplication.getInstence(),"点击成功!",Toast.LENGTH_SHORT).show();
Log.e(TAG, "onSuccess --> 自动点击成功!"+LINE_SEP);
taskOver();
}
@Override
public void onError(String msg) {
Toast.makeText(myApplication.getInstence(),"点击失败:"+msg,Toast.LENGTH_LONG).show();
Log.e(TAG, "onError --> " + msg+LINE_SEP);
taskOver();
......
package com.xf.weixinclick.core.logger;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class LogDB extends SQLiteOpenHelper {
private static final String DB_NAME = "wx_log.db";
private static final String DB_TABLE = "tb_log";
private static final int DB_VER=1;
private static final String COLUMN_LOG_ID = "log_id";
private static final String COLUMN_LOG_TEXT ="log";
private static final String COLUMN_LOG_TIME ="time";
private static final String CREATE_SQL = "CREATE TABLE IF NOT EXISTS "
+DB_TABLE+" ( _id integer primary key autoincrement, "+COLUMN_LOG_ID+" text,"+COLUMN_LOG_TEXT+" text,"
+COLUMN_LOG_TIME +" int);";
public LogDB(Context context) {
super(context, DB_NAME, null, DB_VER);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void clear(){
getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
}
public void addLog(LogMsg msg){
try {
ContentValues values=new ContentValues(3);
values.put(COLUMN_LOG_ID,msg.logId);
values.put(COLUMN_LOG_TEXT,msg.log);
values.put(COLUMN_LOG_TIME,msg.time);
getWritableDatabase().insert(DB_TABLE,null,values);
} catch (Exception e) {
e.printStackTrace();
}
}
public List<LogMsg> getLogs(){
List<LogMsg> logMsgs = new ArrayList<>();
Cursor cursor = null;
try {
cursor = getReadableDatabase()
.query(DB_TABLE, new String[]{COLUMN_LOG_ID,COLUMN_LOG_TEXT,COLUMN_LOG_TIME}, null, null, null, null, COLUMN_LOG_TIME + " desc");
while (cursor.moveToNext()){
LogMsg logMsg = new LogMsg();
logMsg.logId = cursor.getString(0);
logMsg.log = cursor.getString(1);
logMsg.time = cursor.getLong(2);
logMsgs.add(logMsg);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(cursor != null){
cursor.close();
}
}
return logMsgs;
}
}
package com.xf.weixinclick.core.logger;
public class LogMsg {
public String logId;
public String log;
public long time;
}
......@@ -3,6 +3,7 @@ package com.xf.weixinclick.http;
import java.util.Map;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import rx.Observable;
......@@ -23,4 +24,8 @@ public interface ClientApi{
Observable<String> devicesEnable(@Body Map<String, String> params);
@POST("devices/log")
Observable<String> devicesLog(@Body Map<String, String> params);
@GET("devices/get-qr")
Observable<String> getQR();
}
......@@ -5,6 +5,7 @@ import android.util.Log;
import com.google.gson.Gson;
import com.xf.weixinclick.http.stringfactory.StringConverterFactory;
import com.xf.weixinclick.utils.JsonKit;
import com.xf.weixinclick.utils.SP;
import com.xf.weixinclick.BuildConfig;
import com.xf.weixinclick.myApplication;
......@@ -33,14 +34,14 @@ import rx.schedulers.Schedulers;
* Email:liyawei@checheng.com
*/
public class HttpClientApi {
final static int DEFAULT_TIMEOUT = 30;
private final static int DEFAULT_TIMEOUT = 30;
final static Scheduler io = Schedulers.io();
final static Scheduler main = AndroidSchedulers.mainThread();
private final static Scheduler io = Schedulers.io();
private final static Scheduler main = AndroidSchedulers.mainThread();
static String TEST_URL = "http://test.mp-watch.checheng.net/api/";//"http://118.178.135.158:8080/api/";
static String REAL_URL = "http://mp-watch.checheng.net/api/";
static String BASE_URL;
private static String TEST_URL = "http://test.mp-watch.checheng.net/api/";//"http://118.178.135.158:8080/api/";
private static String REAL_URL = "http://mp-watch.checheng.net/api/";
private static String BASE_URL;
public static String getUrl() {
initBaseUrl();
......@@ -60,8 +61,8 @@ public class HttpClientApi {
}
}
static HttpClientApi httpClient = new HttpClientApi();
static Retrofit retrofit;
private static HttpClientApi httpClient = new HttpClientApi();
private static Retrofit retrofit;
private HttpClientApi() {
initBaseUrl();
......@@ -76,7 +77,7 @@ public class HttpClientApi {
String content = response.body().string();
//存入Session
if (response.code() != 200) {
ResponseBase responseBase = new Gson().fromJson(content, ResponseBase.class);
ResponseBase responseBase = JsonKit.GSON.fromJson(content, ResponseBase.class);
myApplication.showToast(responseBase.getMessage() + " "+response.code());
if (response.code() == 401) {
myApplication.startLogin();
......@@ -196,4 +197,22 @@ public class HttpClientApi {
.observeOn(io)
.subscribe(subscriber);
}
public static void uploadDeviceLog(String device_code, String name,String message, Subscriber<String> subscriber) {
Map<String, String> map = new HashMap<>();
map.put("code", device_code);
map.put("name", name);
map.put("msg",message);
getInstance().devicesLog(map)
.subscribeOn(io)
.observeOn(io)
.subscribe(subscriber);
}
public static void getQr(Subscriber<String> subscriber){
getInstance().getQR().subscribeOn(io)
.observeOn(main)
.subscribe(subscriber);;
}
}
......@@ -19,6 +19,7 @@ import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonWriter;
import com.xf.weixinclick.utils.JsonKit;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
......@@ -42,7 +43,7 @@ final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
@Override public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
JsonWriter jsonWriter = new Gson().newJsonWriter(writer);
JsonWriter jsonWriter = JsonKit.GSON.newJsonWriter(writer);
adapter.write(jsonWriter, value);
jsonWriter.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
......
......@@ -19,6 +19,7 @@ import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.xf.weixinclick.utils.JsonKit;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
......@@ -57,7 +58,7 @@ public final class StringConverterFactory extends Converter.Factory {
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeAdapter<?> adapter = new Gson().getAdapter(TypeToken.get(type));
TypeAdapter<?> adapter = JsonKit.GSON.getAdapter(TypeToken.get(type));
return new GsonRequestBodyConverter<>(adapter);
}
}
......@@ -19,6 +19,7 @@ import com.xf.weixinclick.core.MsgSender;
import com.xf.weixinclick.myApplication;
import com.xf.weixinclick.utils.Accessibilitys;
import com.xf.weixinclick.utils.JsonKit;
import org.greenrobot.eventbus.EventBus;
import java.text.SimpleDateFormat;
......@@ -66,7 +67,7 @@ public class MyMessageReceiver extends MessageReceiver {
new Thread(new Runnable() {
@Override
public void run() {
ReceiverMsg msg = new Gson().fromJson(cPushMessage.getContent(), ReceiverMsg.class);
ReceiverMsg msg = JsonKit.GSON.fromJson(cPushMessage.getContent(), ReceiverMsg.class);
long second = System.currentTimeMillis()/1000 - msg.getPushed_at() ;
if (second < 15*60){
......
package com.xf.weixinclick.utils;
import com.google.gson.Gson;
public class JsonKit {
public static final Gson GSON = new Gson();
}
......@@ -52,6 +52,29 @@
android:text="重启网络"
android:layout_margin="4dp"
/>
<Button
android:id="@+id/btn_start_act"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开微信web"
android:layout_margin="4dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="@+id/btn_test_qr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="手动获取登录消息"
/>
</LinearLayout>
</LinearLayout>
\ No newline at end of file
......@@ -4,7 +4,7 @@ import java.util.regex.Pattern
def bakPath = file("${buildDir}/bakApk/")
def baseInfo = "app-1.5.5-0409-13-15-18"
def appVersionName="1.5.5"
def appVersionName="1.5.8"
def variantName = "release"
tinkerpatchSupport {
......
......@@ -9,11 +9,10 @@ buildscript {
'buildToolsVersion' : '27.0.3',
'minSdkVersion' : 21,
'targetSdkVersion' : 27,
'supportLibVersion' : '27.1.0',
'supportLibVersion' : '27.1.1',
'applicationId':'com.xf.weixinclick',
'butterknife' : '8.2.1',
'retrofit' : '2.3.0',
'kotlinVersion' : '1.2.31'
'retrofit' : '2.3.0'
]
......@@ -25,7 +24,7 @@ buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
classpath("com.tinkerpatch.sdk:tinkerpatch-gradle-plugin:1.2.2"){ changing = true }
classpath("com.tinkerpatch.sdk:tinkerpatch-gradle-plugin:1.2.6"){ changing = true }
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment