Commit 5dd575b0 by jeffrey

增加队列 但是有个问题 第一次打开后无响应

parents ad0a2b93 caf4e2f3
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="E:/tools/gradle" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/agent" />
<option value="$PROJECT_DIR$/agentcommon" />
<option value="$PROJECT_DIR$/agentlib" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/debugTools" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
...@@ -2,7 +2,12 @@ ...@@ -2,7 +2,12 @@
<project version="4"> <project version="4">
<component name="ProjectModuleManager"> <component name="ProjectModuleManager">
<modules> <modules>
<module fileurl="file://$PROJECT_DIR$/agent/agent.iml" filepath="$PROJECT_DIR$/agent/agent.iml" />
<module fileurl="file://$PROJECT_DIR$/agentcommon/agentcommon.iml" filepath="$PROJECT_DIR$/agentcommon/agentcommon.iml" />
<module fileurl="file://$PROJECT_DIR$/agentlib/agentlib.iml" filepath="$PROJECT_DIR$/agentlib/agentlib.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" /> <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/debugTools/debugTools.iml" filepath="$PROJECT_DIR$/debugTools/debugTools.iml" />
<module fileurl="file://E:\work\wx_click\wechat_click.iml" filepath="E:\work\wx_click\wechat_click.iml" />
<module fileurl="file://$PROJECT_DIR$/wx_click.iml" filepath="$PROJECT_DIR$/wx_click.iml" /> <module fileurl="file://$PROJECT_DIR$/wx_click.iml" filepath="$PROJECT_DIR$/wx_click.iml" />
</modules> </modules>
</component> </component>
......
...@@ -4,3 +4,31 @@ ...@@ -4,3 +4,31 @@
1. 注意第一次打开微信的时候 手动点击下文件传输助手,确保文件传输助手在第一行 1. 注意第一次打开微信的时候 手动点击下文件传输助手,确保文件传输助手在第一行
1. 修改测试服务器地址后需要杀掉APP 重新打开 1. 修改测试服务器地址后需要杀掉APP 重新打开
1. 如果上述都设置好了后,还是无法自动点击。重启下手机再试 1. 如果上述都设置好了后,还是无法自动点击。重启下手机再试
#### 热更新用法
1. 修改tinkerpatch.gradle,更新appVersionName版本,e.g `def appVersionName="1.5.5"`
2. 运行 `gradle assembleRelease`
在app/build/bakApk/目录下会生成类似`app-1.5.5-0409-13-15-18` 这样的文件夹
全量安装包在`app/build/bakApk/app-xxx/release/app-release.apk`
生成补丁文件
1. 修改tinkerpatch.gradle
```
//全量包版本号
def appVersionName="1.5.5"
//全量包所在目录
def baseInfo = "app-1.5.5-0409-13-15-18"
```
2. 运行 `gradle tinkerPatchRelease` ,补丁文件在`build/outputs/tinkerPatch` 下,登录http://tinkerpatch.com/
选择补丁对应的版本,上传`patch_signed.apk` 文件
参考
http://tinkerpatch.com/Docs/SDK
\ No newline at end of file
生成agent.jar,然后通过命令行
`
export CLASSPATH=/sdcard/Android/data/com.xf.weixinclick/agent.jar
exec app_process /system/bin --nice-name=wx_agent_server com.xf.agent.AgentMain
`
这种方式执行,只能得到部分system context,不能注册/启动组件,可以发送广播
\ No newline at end of file
import java.util.zip.ZipFile
apply plugin: 'com.android.library'
android {
compileSdkVersion versions.compileSdkVersion
buildToolsVersion versions.buildToolsVersion
defaultConfig {
minSdkVersion versions.minSdkVersion
targetSdkVersion versions.targetSdkVersion
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main.java.srcDirs += findProjectSource('agentcommon')+'/java'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
}
def toPath(String s){
if(isWin()){
return s.replace('/','\\')
}else {
return s
}
}
def isWin(){
return org.gradle.internal.os.OperatingSystem.current().isWindows()
}
String.metaClass.toPath = { -> toPath(delegate) }
def findProjectSource(String projectName){
def project = project(":$projectName")
return project.projectDir.absolutePath+"/src/main"
}
def findSdkHome() {
def sdkHome = null
def pFile = project.rootProject.file("local.properties")
if (pFile.exists()) {
def myProp = new Properties()
pFile.withReader {
r -> myProp.load(r)
}
sdkHome = myProp.getProperty("sdk.dir")
}
if (sdkHome == null) {
sdkHome = System.getenv("ANDROID_HOME")
}
if(sdkHome?.trim()?.isEmpty()){
throw new RuntimeException("not found android sdk environment !")
}
return sdkHome
}
def jar2dex(File jarFile,File out){
//java jar to dex file
println("------jar2dex------")
// find sdk home dir.
def sdkHome = findSdkHome()
println("android sdk home:${sdkHome}")
def dxFile=file("${sdkHome}/build-tools/${versions.buildToolsVersion}/dx${isWin()?'.bat':''}".toPath())
if(dxFile.exists()){
dxFile.setExecutable(true)
}else {
throw new RuntimeException("not found dx executable file in path ${dxFile}")
}
println("dx binary file:${dxFile}")
def cmdArgs=['--dex',"--output=${out.absolutePath}",jarFile.absolutePath]
exec{
executable=dxFile
args=cmdArgs
}
println("----jar2dex success,exec end----")
}
build.doLast {
//复制agent.jar到 agent/build 目录下
def target = file("${project.buildDir}/agent.jar")
def destDex = file("${findProjectSource('agentlib')}/assets/agent.jar")
new ZipFile("${project.buildDir}/outputs/aar/agent-debug.aar").withCloseable {
it.getInputStream(it.getEntry("classes.jar")).withStream{
def ins = it
target.getParentFile().mkdirs()
target.withOutputStream {
it << ins
}
}
}
jar2dex(target,destDex)
}
\ No newline at end of file
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xf.agent"/>
package android.app;
public class ActivityManagerNative {
static public IActivityManager getDefault() {
return null;
}
}
package android.app;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
/**
* Created by zl on 2016/11/5.
*/
public class ActivityThread {
public static IPackageManager getPackageManager() {
return null;
}
public static ActivityThread systemMain() {
return null;
}
public static ActivityThread currentActivityThread() {
return null;
}
public static Application currentApplication() {
return null;
}
public static String currentProcessName() {
return null;
}
public ContextImpl getSystemContext() {
return null;
}
public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
}
}
package android.app;
import android.content.Context;
/**
* Created by zl on 2017/2/13.
*/
public abstract class ContextImpl extends Context{
}
package android.app;
import android.content.ContentProviderNative;
import android.content.IContentProvider;
import android.content.pm.ProviderInfo;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.RemoteException;
public interface IActivityManager {
public ContentProviderHolder getContentProviderExternal(String name, int userId, IBinder token) throws RemoteException;
public void removeContentProviderExternal(String name, IBinder token) throws RemoteException;
/*
* Private non-Binder interfaces
*/
/* package */ boolean testIsSystemReady();
/** Information you can retrieve about a particular application. */
public static class ContentProviderHolder implements Parcelable {
public final ProviderInfo info;
public IContentProvider provider;
public IBinder connection;
public boolean noReleaseNeeded;
public ContentProviderHolder(ProviderInfo _info) {
info = _info;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
info.writeToParcel(dest, 0);
if (provider != null) {
dest.writeStrongBinder(provider.asBinder());
} else {
dest.writeStrongBinder(null);
}
dest.writeStrongBinder(connection);
dest.writeInt(noReleaseNeeded ? 1 : 0);
}
public static final Parcelable.Creator<ContentProviderHolder> CREATOR
= new Parcelable.Creator<ContentProviderHolder>() {
@Override
public ContentProviderHolder createFromParcel(Parcel source) {
return new ContentProviderHolder(source);
}
@Override
public ContentProviderHolder[] newArray(int size) {
return new ContentProviderHolder[size];
}
};
private ContentProviderHolder(Parcel source) {
info = ProviderInfo.CREATOR.createFromParcel(source);
provider = ContentProviderNative.asInterface(
source.readStrongBinder());
connection = source.readStrongBinder();
noReleaseNeeded = source.readInt() != 0;
}
}
}
package android.content;
import android.os.IBinder;
public class ContentProviderNative {
static public IContentProvider asInterface(IBinder obj){
return null;
}
}
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.content;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.RemoteException;
import java.util.ArrayList;
/**
* The ipc interface to talk to a content provider.
* @hide
*/
public interface IContentProvider extends IInterface {
// public Cursor query(String callingPkg, Uri url, String[] projection, String selection,
// String[] selectionArgs, String sortOrder, ICancellationSignal cancellationSignal)
// throws RemoteException;
public String getType(Uri url) throws RemoteException;
public Uri insert(String callingPkg, Uri url, ContentValues initialValues)
throws RemoteException;
public int bulkInsert(String callingPkg, Uri url, ContentValues[] initialValues)
throws RemoteException;
public int delete(String callingPkg, Uri url, String selection, String[] selectionArgs)
throws RemoteException;
public int update(String callingPkg, Uri url, ContentValues values, String selection,
String[] selectionArgs) throws RemoteException;
public ContentProviderResult[] applyBatch(String callingPkg,
ArrayList<ContentProviderOperation> operations)
throws RemoteException, OperationApplicationException;
public Bundle call(
String callingPkg, String method, String arg, Bundle extras)
throws RemoteException;
public Uri canonicalize(String callingPkg, Uri uri) throws RemoteException;
public Uri uncanonicalize(String callingPkg, Uri uri) throws RemoteException;
// Data interchange.
public String[] getStreamTypes(Uri url, String mimeTypeFilter) throws RemoteException;
}
package android.content.pm;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
/**
* Created by zl on 2017/7/31.
*/
public interface IPackageManager {
PackageInfo getPackageInfo(String packageName, int flags, int userId);
PermissionInfo getPermissionInfo(String name, int flags);
PermissionGroupInfo getPermissionGroupInfo(String name, int flags);
void grantRuntimePermission(String packageName, String permissionName, int userId);
void revokeRuntimePermission(String packageName, String permissionName, int userId);
void resetRuntimePermissions();
int getPermissionFlags(String permissionName, String packageName, int userId);
String[] getAppOpPermissionPackages(String permissionName);
ResolveInfo resolveIntent(Intent intent, String resolvedType, int flags, int userId);
ApplicationInfo getApplicationInfo(String packageName, int flags, int userId);
ParceledListSlice getInstalledPackages(int flags, int userId);
int getPackageUid(String packageName, int flags, int userId);
// for API 23 or lower
int getPackageUid(String packageName, int userId);
}
package android.content.pm;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
public class ParceledListSlice<T extends Parcelable>{
public List<T> getList() {
return null;
}
public void writeToParcel(Parcel dest, int flags) {
}
}
package android.os;
/**
* Created by zl on 2016/11/5.
*/
public class ServiceManager {
public static IBinder getService(String name) {
return null;
}
}
package com.xf.agent;
import android.app.ActivityThread;
import android.content.ComponentName;
import android.content.Context;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityManager;
import com.xf.agent.common.CallRequest;
import com.xf.agent.common.CallResult;
import com.xf.agent.common.CmdResult;
import com.xf.agent.common.MethodUtils;
import com.xf.agent.common.ParcelableUtil;
import com.xf.agent.common.Shell;
import com.xf.agent.common.Shell.Result;
import com.xf.agent.common.TypeCmd;
import com.xf.agent.common.Types;
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.Map;
import java.util.Set;
class AgentHandler implements OpsDataTransfer.OnRecvCallback{
private SkServer server;
private volatile boolean isDeath = false;
private Shell shell;
AgentHandler() throws IOException {
server = new SkServer(this);
shell = Shell.getShell();
}
void start() throws Exception {
server.run();
}
void destory() {
try {
isDeath = true;
server.setStop();
} catch (Exception e) {
e.printStackTrace();
}
}
private Context getContext(){
ActivityThread activityThread = ActivityThread.currentActivityThread();
return activityThread.getSystemContext();
}
@Override
public void onMessage(byte[] bytes) {
try {
Context context = getContext();
//AccessibilityUtils.openSetting(context);
// ComponentName componentName=new ComponentName("com.xf.weixinclick","com.xf.weixinclick.NewService");
// AccessibilityUtils.setAccessibilityServiceState(context,componentName,true);
// FLog.log("log end");
// Set<ComponentName> enabledServicesFromSettings = AccessibilityUtils
// .getEnabledServicesFromSettings(context);
// for (ComponentName enabledServicesFromSetting : enabledServicesFromSettings) {
// FLog.log(enabledServicesFromSetting.toShortString());
// }
} catch (Exception e) {
e.printStackTrace();
FLog.log(e);
}
if (!isDeath) {
LifecycleAgent.serverRunInfo.recvBytes += bytes.length;
CallResult result=new CallResult();
try {
CallRequest callRequest = ParcelableUtil.unmarshall(bytes, CallRequest.CREATOR);
result.reqId = callRequest.id;
FLog.log(callRequest.toString());
if(callRequest.type == Types.CMD){
TypeCmd typeCmd = ParcelableUtil.unmarshall(callRequest.data, TypeCmd.CREATOR);
if(shell.isClose()){
shell=Shell.getShell();
}
Result execResult = shell.exec(typeCmd.command);
FLog.log(execResult.toString());
CmdResult cmdResult = new CmdResult();
cmdResult.code = execResult.getStatusCode();
cmdResult.message = execResult.getMessage();
result.data = ParcelableUtil.marshall(cmdResult);
}else if(callRequest.type == Types.CLOSE){
destory();
}else if(callRequest.type == Types.RESTART){
}else if(callRequest.type == Types.RESTART_NETWORK){
//
IBinder service = ServiceManager.getService(Context.TELEPHONY_SERVICE);
MethodUtils.invokeExactMethod(service,"setDataEnabled",false);
SystemClock.sleep(2000);
MethodUtils.invokeExactMethod(service,"setDataEnabled",true);
FLog.log("---restart network success --- ");
}else {
System.out.println("unknown type !");
}
} catch (Exception e) {
result.throwable = e;
e.printStackTrace();
} finally {
sendResult(result);
}
}
}
private void sendResult(Parcelable result) {
try {
server.sendResult(ParcelableUtil.marshall(result));
} catch (IOException e) {
e.printStackTrace();
FLog.log(e);
}
}
}
package com.xf.agent;
import android.app.ActivityThread;
import android.os.Build;
import android.os.Looper;
import android.os.Process;
import android.os.SystemClock;
import android.system.Os;
import android.text.TextUtils;
import com.xf.agent.common.server.FLog;
import com.xf.agent.common.server.OpsDataTransfer;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class AgentMain {
public static void main(String[] args) {
try {
FLog.writeLog = true;
FLog.log("start agent server args:" + Arrays.toString(args));
if (args == null) {
return;
}
Looper.prepareMainLooper();
ActivityThread.systemMain();
LifecycleAgent.serverRunInfo.startTime = System.currentTimeMillis();
LifecycleAgent.serverRunInfo.startRealTime = SystemClock.elapsedRealtime();
if(args.length > 1 && !TextUtils.isEmpty(args[1])){
killOld(args[1]);
SystemClock.sleep(1000);
}
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
try {
new AgentMain();
} catch (Exception e) {
e.printStackTrace();
FLog.log(e);
}finally {
FLog.close();
stop();
}
}
});
thread.setName("IPC-agent");
thread.start();
Looper.loop();
} catch (Throwable e) {
e.printStackTrace();
FLog.log(e);
} finally {
FLog.log("close log ... ");
FLog.close();
}
stop();
}
private static void killOld(String pid){
try{
int oldPid = Integer.parseInt(pid);
String processName = getProcessName(oldPid);
if("wx_agent_server".equals(processName)){
Process.killProcess(oldPid);
FLog.log("killed pid : "+pid);
}
}catch (Throwable throwable){
FLog.log(throwable);
}
}
private static void stop(){
int pid = Process.myPid();
System.out.println(" STOP: kill myself ---- pid: " + pid);
killProcess(pid);
}
private static void killProcess(int pid){
try {
Process.killProcess(pid);
} catch (Throwable e) {
e.printStackTrace();
}finally {
try {
//only killProcess fail will be call.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Os.execve("/system/bin/kill", new String[]{"-9", String.valueOf(pid)}, null);
} else {
Runtime.getRuntime().exec("kill -9 " + pid);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
private AgentHandler mCallHandler;
private AgentMain() throws Exception {
try {
mCallHandler = new AgentHandler();
System.out.println("Agent server start successful, enjoy it! \uD83D\uDE0E");
int pid = Process.myPid();
System.out.println(getProcessName(pid)+" pid:"+ pid);
LifecycleAgent.onStarted();
mCallHandler.start();
}catch (OpsDataTransfer.ProtocolVersionException e){
// server side is old version, restart server
Runtime.getRuntime().exec("sh /sdcard/Android/data/com.xf.weixinclick/agent.sh "+ Process.myPid());
SystemClock.sleep(1000);
}catch (Throwable throwable){
FLog.log(throwable);
}finally {
destory();
}
}
private void destory() {
try {
if(mCallHandler != null){
mCallHandler.destory();
}
FLog.log("handler destory ----- ");
} catch (Exception e) {
e.printStackTrace();
FLog.log(e);
}
LifecycleAgent.onStoped();
}
private static String getProcessName(int pid){
FileInputStream fis = null;
try {
byte[] buff = new byte[512];
fis = new FileInputStream("/proc/"+pid+"/cmdline");
int len = fis.read(buff);
if (len > 0) {
int i;
for (i=0; i<len; i++) {
if (buff[i] == '\0') {
break;
}
}
return new String(buff,0,i);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
package com.xf.agent;
import android.app.ActivityThread;
import android.content.Intent;
import com.xf.agent.common.server.FLog;
class ApiCompat {
static void sendBroadcast(Intent intent) {
try {
ActivityThread.currentApplication().sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
FLog.log(e);
}
}
}
\ No newline at end of file
package com.xf.agent;
import android.content.Intent;
import com.xf.agent.common.Actions;
import com.xf.agent.common.server.ServerRunInfo;
import java.util.Map;
class LifecycleAgent {
static volatile Map<String, String> sParams;
static ServerRunInfo serverRunInfo = new ServerRunInfo();
static void onStarted(){
Intent intent = makeIntent(Actions.ACTION_SERVER_STARTED);
ApiCompat.sendBroadcast(intent);
}
static void onConnected(){
Intent intent = makeIntent(Actions.ACTION_SERVER_CONNECTED);
ApiCompat.sendBroadcast(intent);
}
static void onDisconnected(){
Intent intent = makeIntent(Actions.ACTION_SERVER_DISCONNECTED);
ApiCompat.sendBroadcast(intent);
}
static void onStoped(){
Intent intent = makeIntent(Actions.ACTION_SERVER_STOPED);
ApiCompat.sendBroadcast(intent);
}
private static Intent makeIntent(String action){
Intent intent = new Intent(action);
return intent;
}
}
package com.xf.agent;
import com.xf.agent.common.ServerConfig;
import com.xf.agent.common.server.FLog;
import com.xf.agent.common.server.OpsDataTransfer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class SkServer {
private boolean running = true;
private IServer server;
private OpsDataTransfer opsDataTransfer;
private OpsDataTransfer.OnRecvCallback callback;
SkServer( OpsDataTransfer.OnRecvCallback callback)
throws IOException {
server = new NetSocketServerImpl(ServerConfig.PORT);
this.callback = callback;
}
void run() throws Exception {
while (running) {
try {
server.accept();
opsDataTransfer = new OpsDataTransfer(server.getOutputStream(), server.getInputStream(),
callback);
opsDataTransfer.shakehands(ServerConfig.TOKEN, true);
LifecycleAgent.onConnected();
opsDataTransfer.handleRecv();
}catch (OpsDataTransfer.ProtocolVersionException e){
throw e;
}catch (IOException e) {
FLog.log(e);
LifecycleAgent.onDisconnected();
} catch (RuntimeException e) {
FLog.log(e);
LifecycleAgent.onDisconnected();
running = false;
throw e;
}
}
}
public void sendResult(byte[] bytes) throws IOException {
if (running && opsDataTransfer != null) {
LifecycleAgent.serverRunInfo.sentBytes += bytes.length;
opsDataTransfer.sendMsg(bytes);
}
}
public void setStop() {
running = false;
if (opsDataTransfer != null) {
opsDataTransfer.stop();
}
try {
if (server != null) {
server.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private interface IServer {
InputStream getInputStream() throws IOException;
OutputStream getOutputStream() throws IOException;
void accept() throws IOException;
void close() throws IOException;
}
private static class NetSocketServerImpl implements IServer {
private ServerSocket serverSocket;
private Socket socket;
public NetSocketServerImpl(int port) throws IOException {
this.serverSocket = new ServerSocket(port);
}
@Override
public InputStream getInputStream() throws IOException {
return socket.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return socket.getOutputStream();
}
@Override
public void accept() throws IOException {
socket = serverSocket.accept();
}
@Override
public void close() throws IOException {
socket.close();
serverSocket.close();
}
}
}
\ No newline at end of file
<resources>
<string name="app_name">agent</string>
</resources>
用于app <---> agent.jar 之间的通讯和公共类
\ No newline at end of file
apply plugin: 'com.android.library'
android {
compileSdkVersion versions.compileSdkVersion
buildToolsVersion versions.buildToolsVersion
defaultConfig {
minSdkVersion versions.minSdkVersion
targetSdkVersion versions.targetSdkVersion
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
}
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xf.agent.common"/>
package com.xf.agent.common;
public final class Actions {
public static final String ACTION_SERVER_STARTED="com.xf.agent.action.SERVER_STARTED";
public static final String ACTION_SERVER_CONNECTED="com.xf.agent.action.SERVER_CONNECTED";
public static final String ACTION_SERVER_DISCONNECTED="com.xf.agent.action.SERVER_DISCONNECTED";
public static final String ACTION_SERVER_STOPED="com.xf.agent.action.SERVER_STOPED";
}
\ No newline at end of file
package com.xf.agent.common;
import android.os.Parcel;
import android.os.Parcelable.Creator;
public class CallRequest implements android.os.Parcelable {
public int id = Utils.generateSeqId();
public int type;
public byte[] data;
public CallRequest(IReq req) {
type = req.getType();
data = req.getData();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeInt(this.type);
dest.writeByteArray(this.data);
}
public CallRequest() {
}
protected CallRequest(Parcel in) {
this.id = in.readInt();
this.type = in.readInt();
this.data = in.createByteArray();
}
public static final Creator<CallRequest> CREATOR = new Creator<CallRequest>() {
@Override
public CallRequest createFromParcel(Parcel source) {
return new CallRequest(source);
}
@Override
public CallRequest[] newArray(int size) {
return new CallRequest[size];
}
};
@Override
public String toString() {
return "CallRequest{" +
"id=" + id +
", type=" + type +
'}';
}
}
package com.xf.agent.common;
import android.os.Parcel;
import android.os.Parcelable.Creator;
public class CallResult implements android.os.Parcelable {
public int id;
public int reqId;
public Throwable throwable;
public byte[] data;
public transient CallRequest request;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeInt(this.reqId);
dest.writeSerializable(this.throwable);
dest.writeByteArray(this.data);
}
public CallResult() {
}
protected CallResult(Parcel in) {
this.id = in.readInt();
this.reqId = in.readInt();
this.throwable = (Throwable) in.readSerializable();
this.data = in.createByteArray();
}
public static final Creator<CallResult> CREATOR = new Creator<CallResult>() {
@Override
public CallResult createFromParcel(Parcel source) {
return new CallResult(source);
}
@Override
public CallResult[] newArray(int size) {
return new CallResult[size];
}
};
}
package com.xf.agent.common;
import android.os.Parcel;
import android.os.Parcelable.Creator;
public class CmdResult implements android.os.Parcelable {
public int code;
public String message;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.code);
dest.writeString(this.message);
}
public CmdResult() {
}
protected CmdResult(Parcel in) {
this.code = in.readInt();
this.message = in.readString();
}
public static final Creator<CmdResult> CREATOR = new Creator<CmdResult>() {
@Override
public CmdResult createFromParcel(Parcel source) {
return new CmdResult(source);
}
@Override
public CmdResult[] newArray(int size) {
return new CmdResult[size];
}
};
@Override
public String toString() {
return "CmdResult{" +
"code=" + code +
", message='" + message + '\'' +
'}';
}
}
package com.xf.agent.common;
public interface IReq {
int getType();
byte[] getData();
}
package com.xf.agent.common;
import android.os.Parcel;
import android.os.Parcelable.Creator;
public class NormalCmd implements IReq, android.os.Parcelable {
public int type;
public NormalCmd(int type) {
this.type = type;
}
public NormalCmd() {
}
@Override
public int getType() {
return 0;
}
@Override
public byte[] getData() {
return new byte[0];
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.type);
}
protected NormalCmd(Parcel in) {
this.type = in.readInt();
}
public static final Creator<NormalCmd> CREATOR = new Creator<NormalCmd>() {
@Override
public NormalCmd createFromParcel(Parcel source) {
return new NormalCmd(source);
}
@Override
public NormalCmd[] newArray(int size) {
return new NormalCmd[size];
}
};
}
package com.xf.agent.common;
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelableUtil {
public static byte[] marshall(Parcelable parceable) {
Parcel parcel = Parcel.obtain();
parceable.writeToParcel(parcel, 0);
byte[] bytes = parcel.marshall();
parcel.recycle();
return bytes;
}
public static <T extends Parcelable> T unmarshall(byte[] bytes, Parcelable.Creator<T> creator) {
if(bytes == null){
return null;
}
Parcel parcel = unmarshall(bytes);
return creator.createFromParcel(parcel);
}
public static Parcel unmarshall(byte[] bytes) {
if(bytes == null){
return null;
}
Parcel parcel = Parcel.obtain();
parcel.unmarshall(bytes, 0, bytes.length);
parcel.setDataPosition(0);
return parcel;
}
public static Object readValue(byte[] bytes){
if(bytes == null){
return null;
}
Parcel unmarshall = unmarshall(bytes);
Object o = unmarshall.readValue(ParcelableUtil.class.getClassLoader());
unmarshall.recycle();
return o;
}
}
\ No newline at end of file
package com.xf.agent.common;
public final class ServerConfig {
public static final int PORT = 33407;
public static final String TOKEN = "$1$EqQamPKn$gq0Wj0szGRUHz/HVrydmj0$1$47CyM0w6$cIASqtwHmdVbHF8OKH5fF/";
}
package com.xf.agent.common;
import android.os.Parcel;
import android.os.Parcelable.Creator;
public class TypeCmd implements IReq,android.os.Parcelable {
public int uid;
public String command;
public TypeCmd(String command) {
this.command = command;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.uid);
dest.writeString(this.command);
}
public TypeCmd() {
}
protected TypeCmd(Parcel in) {
this.uid = in.readInt();
this.command = in.readString();
}
public static final Creator<TypeCmd> CREATOR = new Creator<TypeCmd>() {
@Override
public TypeCmd createFromParcel(Parcel source) {
return new TypeCmd(source);
}
@Override
public TypeCmd[] newArray(int size) {
return new TypeCmd[size];
}
};
@Override
public int getType() {
return Types.CMD;
}
@Override
public byte[] getData() {
return ParcelableUtil.marshall(this);
}
}
package com.xf.agent.common;
public final class Types {
/**
* 执行命令
*/
public static final int CMD = 1;
/**
* 关闭服务
*/
public static final int CLOSE = 2;
/**
* 重启服务
*/
public static final int RESTART = 3;
/**
* 重启4G网络
*/
public static final int RESTART_NETWORK = 4;
}
package com.xf.agent.common;
import android.view.View;
import java.util.concurrent.atomic.AtomicInteger;
class Utils {
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
static int generateSeqId() {
for (;;) {
final int result = sNextGeneratedId.get();
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1;
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
}
private static void fv(){
}
}
package com.xf.agent.common.server;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.system.Os;
import android.system.OsConstants;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
public class FLog {
public static boolean writeLog = false;
private static FileOutputStream fos;
private static AtomicInteger sBufferSize = new AtomicInteger();
private static AtomicInteger sErrorCount = new AtomicInteger();
private static void openFile() {
try {
if (writeLog && fos == null && sErrorCount.get() < 5) {
File file = new File("/data/local/tmp/wx_agent_log.txt");
fos = new FileOutputStream(file);
fos.write("\n\n\n--------------------".getBytes());
fos.write(new Date().toString().getBytes());
fos.write("\n\n".getBytes());
chown(file.getAbsolutePath(),2000,2000);
chmod(file.getAbsolutePath(),0755);
}
} catch (Exception e) {
e.printStackTrace();
sErrorCount.incrementAndGet();
fos = null;
}
}
private static void chown(String path, int uid, int gid){
try {
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
Os.chown(path,uid,gid);
}else {
Runtime.getRuntime().exec("chown "+uid+":"+gid+" "+path).destroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void chmod(String path,int mode){
try {
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
Os.chmod(path, mode);
}else {
Runtime.getRuntime().exec("chmod "+mode+" "+path).destroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void log(String log) {
if (writeLog) {
System.out.println(log);
} else {
Log.e("appopsx", "Flog --> " + log);
}
try {
if (writeLog) {
openFile();
if (fos != null) {
fos.write(log.getBytes());
fos.write("\n".getBytes());
if (sBufferSize.incrementAndGet() > 10) {
fos.getFD().sync();
fos.flush();
sBufferSize.set(0);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void log(Throwable e) {
log(Log.getStackTraceString(e));
}
public static void close() {
try {
if (writeLog && fos != null) {
fos.getFD().sync();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.xf.agent.common.server;
import android.text.TextUtils;
import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by zl on 2016/11/5.
*/
public class OpsDataTransfer {
// length+data
public static final String PROTOCOL_VERSION = "1.0";
private DataOutputStream outputStream;
private DataInputStream inputStream;
private OnRecvCallback callback;
private boolean running = true;
private boolean async = true;
public OpsDataTransfer(OutputStream outputStream, InputStream inputStream,
OnRecvCallback callback) {
this.outputStream = new DataOutputStream(outputStream);
this.inputStream = new DataInputStream(inputStream);
this.callback = callback;
}
public OpsDataTransfer(OutputStream outputStream, InputStream inputStream) {
this(outputStream, inputStream, true);
}
public OpsDataTransfer(OutputStream outputStream, InputStream inputStream, boolean async) {
this(outputStream, inputStream, null);
this.async = async;
}
public void setCallback(OnRecvCallback callback) {
this.callback = callback;
}
public void sendMsg(String text) throws IOException {
if (text != null) {
sendMsg(text.getBytes());
}
}
public void sendMsg(byte[] msg) throws IOException {
if (msg != null) {
outputStream.writeInt(msg.length);
outputStream.write(msg);
outputStream.flush();
}
}
private byte[] readMsg() throws IOException {
int len = inputStream.readInt();
byte[] bytes = new byte[len];
inputStream.readFully(bytes, 0, len);
return bytes;
}
public synchronized byte[] sendMsgAndRecv(byte[] msg) throws IOException {
if (msg != null) {
sendMsg(msg);
return readMsg();
}
return null;
}
public interface OnRecvCallback {
void onMessage(byte[] bytes);
}
public void shakehands(String token, boolean isServer) throws IOException {
if (token == null) {
return;
}
if (isServer) {
FLog.log("shakehands --> start: token " + token + " " + isServer + " server protocol :"
+ PROTOCOL_VERSION);
} else {
Log.e("test", "shakehands --> start: token " + token + " " + isServer + " client protocol:"
+ PROTOCOL_VERSION);
}
if (isServer) {
String auth = new String(readMsg());
FLog.log("recv auth " + auth);
String[] split = auth.split(",");
String recvToken = split[1];
if (TextUtils.equals(token, recvToken)) {
//auth success,pass
FLog.log("shakehands --> hands success ");
} else {
FLog.log("shakehands --> unknow token ");
throw new RuntimeException("Unauthorized client, token:" + token);
}
String ver = split[0];
if (!TextUtils.equals(ver, PROTOCOL_VERSION)) {
throw new ProtocolVersionException(
"client protocol version:" + ver + " ,server protocol version:" + PROTOCOL_VERSION);
}
} else {
//client
sendMsg(PROTOCOL_VERSION + "," + token);
}
}
public void handleRecv() throws IOException {
if (!async) {
return;
}
while (running) {
// int len = inputStream.readInt();
// byte[] bytes = new byte[len];
// if(inputStream.read(bytes, 0, len) == len){
// onRecvMsg(bytes);
// }
onRecvMsg(readMsg());
}
}
private void onRecvMsg(byte[] bytes) {
if (callback != null) {
callback.onMessage(bytes);
}
}
public void stop() {
running = false;
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static class ProtocolVersionException extends IOException{
public ProtocolVersionException(String message) {
super(message);
}
public ProtocolVersionException(String message, Throwable cause) {
super(message, cause);
}
public ProtocolVersionException(Throwable cause) {
super(cause);
}
}
}
package com.xf.agent.common.server;
import android.os.Parcel;
public class ServerRunInfo implements android.os.Parcelable {
public String protocolVersion = OpsDataTransfer.PROTOCOL_VERSION;
public long startTime;
public long startRealTime;
public long recvBytes;
public long sentBytes;
public long successCount;
public long errorCount;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.protocolVersion);
dest.writeLong(this.startTime);
dest.writeLong(this.startRealTime);
dest.writeLong(this.recvBytes);
dest.writeLong(this.sentBytes);
dest.writeLong(this.successCount);
dest.writeLong(this.errorCount);
}
public ServerRunInfo() {
}
protected ServerRunInfo(Parcel in) {
this.protocolVersion = in.readString();
this.startTime = in.readLong();
this.startRealTime = in.readLong();
this.recvBytes = in.readLong();
this.sentBytes = in.readLong();
this.successCount = in.readLong();
this.errorCount = in.readLong();
}
public static final Creator<ServerRunInfo> CREATOR = new Creator<ServerRunInfo>() {
@Override
public ServerRunInfo createFromParcel(Parcel source) {
return new ServerRunInfo(source);
}
@Override
public ServerRunInfo[] newArray(int size) {
return new ServerRunInfo[size];
}
};
@Override
public String toString() {
return "ServerRunInfo{" +
"protocolVersion='" + protocolVersion + '\'' +
", startTime=" + startTime +
", startRealTime=" + startRealTime +
", recvBytes=" + recvBytes +
", sentBytes=" + sentBytes +
", successCount=" + successCount +
", errorCount=" + errorCount +
'}';
}
}
<resources>
<string name="app_name">agentcommon</string>
</resources>
/build
agent.jar
\ No newline at end of file
代理执行agent,拥有root/shell权限,能以root/shell权限调用部分系统隐藏api
\ No newline at end of file
apply plugin: 'com.android.library'
android {
compileSdkVersion versions.compileSdkVersion
buildToolsVersion versions.buildToolsVersion
defaultConfig {
minSdkVersion versions.minSdkVersion
targetSdkVersion versions.targetSdkVersion
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
api project(":agentcommon")
}
//编译前先生成agent.jar
preBuild.dependsOn ":agent:build"
\ No newline at end of file
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xf.agent.wrap"/>
#!/system/bin/sh
echo '---start'
export CLASSPATH=/sdcard/Android/data/com.xf.weixinclick/agent.jar
exec app_process /system/bin --nice-name=wx_agent_server com.xf.agent.AgentMain $@ &
echo $?
package com.xf.agent.wrap;
import android.content.Context;
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;
public class AgentManager {
private static final String TAG = "AgentManager";
private LocalServerManager mLocalServerManager;
public AgentManager(Context context) {
SConfig.init(context);
mLocalServerManager = LocalServerManager.getInstance();
}
private synchronized void checkConnect() throws Exception {
mLocalServerManager.start();
}
public CmdResult exeCommand(String cmd)throws Throwable{
checkConnect();
TypeCmd typeCmd = new TypeCmd(cmd);
CallResult result = mLocalServerManager.execNew(typeCmd);
if(result!= null && result.throwable != null){
throw result.throwable;
}
return ParcelableUtil.unmarshall(result.data,CmdResult.CREATOR);
}
public boolean restart4G() throws Throwable {
checkConnect();
NormalCmd normalCmd = new NormalCmd(Types.RESTART_NETWORK);
CallResult result = mLocalServerManager.execNew(normalCmd);
if(result!= null && result.throwable != null){
throw result.throwable;
}
return true;
}
public void destory() {
if (mLocalServerManager != null) {
mLocalServerManager.stop();
}
}
public boolean isRunning() {
return mLocalServerManager != null && mLocalServerManager.isRunning();
}
public void closeBgServer() {
if(mLocalServerManager != null){
mLocalServerManager.closeBgServer();
mLocalServerManager.stop();
}
}
public static boolean isEnableSELinux() {
return AssetsUtils.isEnableSELinux();
}
}
\ No newline at end of file
package com.xf.agent.wrap;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.os.Build;
import android.text.TextUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
class AssetsUtils {
private static final char[] DIGITS_LOWER =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static void copyFile(Context context, String fileName, File destFile, boolean force) {
InputStream open = null;
FileOutputStream fos = null;
try {
AssetFileDescriptor openFd = context.getAssets().openFd(fileName);
if (force) {
destFile.delete();
} else {
if (destFile.exists()) {
if (destFile.length() != openFd.getLength()) {
destFile.delete();
} else {
return;
}
}
}
if (!destFile.exists()) {
destFile.createNewFile();
destFile.setReadable(true, false);
destFile.setExecutable(true, false);
}
fos = new FileOutputStream(destFile);
byte[] buff = new byte[1024 * 16];
int len = -1;
open = openFd.createInputStream();
while ((len = open.read(buff)) != -1) {
fos.write(buff, 0, len);
}
fos.flush();
fos.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (open != null) {
open.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void copyFile(String src,File destFile, boolean force){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcFile=new File(src);
if (force) {
destFile.delete();
} else {
if (destFile.exists()) {
if (destFile.length() != srcFile.length()) {
destFile.delete();
} else {
return;
}
}
}
if (!destFile.exists()) {
destFile.createNewFile();
}
destFile.setReadable(true, false);
destFile.setExecutable(true, false);
fos = new FileOutputStream(destFile);
byte[] buff = new byte[1024 * 16];
int len = -1;
fis = new FileInputStream(srcFile);
while ((len = fis.read(buff)) != -1) {
fos.write(buff, 0, len);
}
fos.flush();
fos.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
static boolean is64Bit() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
String[] supported64BitAbis = Build.SUPPORTED_64_BIT_ABIS;
return supported64BitAbis != null && supported64BitAbis.length > 0;
} else {
return Build.CPU_ABI.equals("arm64-v8a");
}
}
static String generateToken(int len) {
SecureRandom secureRandom = new SecureRandom();
byte[] bytes = new byte[len];
secureRandom.nextBytes(bytes);
return new String(encodeHex(bytes, DIGITS_LOWER));
}
private static char[] encodeHex(final byte[] data, final char[] toDigits) {
final int l = data.length;
final char[] out = new char[l << 1];
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
static boolean isEnableSELinux() {
File f = new File("/sys/fs/selinux/enforce");
String s = null;
if (f.exists() && !TextUtils.isEmpty((s = readProc(f)))) {
return "1".equals(s.trim());
} else {
String getenforce = readCommand("getenforce");
if (!TextUtils.isEmpty(getenforce) && getenforce.contains("Enforcing")) {
return true;
}
}
return false;
}
private static String readProc(File file) {
FileInputStream fis = null;
try {
byte[] buff = new byte[512];
fis = new FileInputStream(file);
int len = fis.read(buff);
if (len > 0) {
int i;
for (i = 0; i < len; i++) {
if (buff[i] == '\0') {
break;
}
}
return new String(buff, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private static String readCommand(String cmd) {
Process exec = null;
InputStream inputStream = null;
try {
exec = Runtime.getRuntime().exec(cmd);
inputStream = exec.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = -1;
while ((len = inputStream.read(buff, 0, buff.length)) != -1) {
baos.write(buff, 0, len);
if (baos.size() >= 128 * 1024) {
break;
}
}
return baos.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (exec != null) {
exec.destroy();
}
}
return null;
}
}
\ No newline at end of file
package com.xf.agent.wrap;
import android.os.SystemClock;
import android.util.Log;
import com.xf.agent.common.CallRequest;
import com.xf.agent.common.CallResult;
import com.xf.agent.common.IReq;
import com.xf.agent.common.NormalCmd;
import com.xf.agent.common.ParcelableUtil;
import com.xf.agent.common.ServerConfig;
import com.xf.agent.common.Types;
import com.xf.agent.common.server.OpsDataTransfer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
class LocalServerManager {
private static final String SH_FILE = SConfig.DIR_PREFIX +"/"+SConfig.SH_NAME;
private static final String TAG = "LocalServerManager";
private static LocalServerManager sLocalServerManager;
static LocalServerManager getInstance() {
if (sLocalServerManager == null) {
synchronized (LocalServerManager.class) {
if (sLocalServerManager == null) {
sLocalServerManager = new LocalServerManager();
}
}
}
return sLocalServerManager;
}
private ClientSession mSession = null;
private LocalServerManager() {
}
private ClientSession getSession() throws Exception {
if (mSession == null || !mSession.isRunning()) {
try {
//try to connect
mSession = createSession();
} catch (Exception e) {
e.printStackTrace();
}
if (mSession == null) {
//server not started
startServer();
mSession = createSession();
}
}
return mSession;
}
public boolean isRunning() {
return mSession != null && mSession.isRunning();
}
void closeSession(){
if (mSession != null) {
mSession.close();
mSession = null;
}
}
void stop() {
if (mSession != null) {
mSession.close();
mSession = null;
}
}
void start() throws Exception {
getSession();
}
private OpsDataTransfer getSessionTransfer() throws Exception {
ClientSession session = getSession();
if(session == null){
throw new RuntimeException("create session error ------");
}
OpsDataTransfer transfer = session.getTransfer();
if(transfer == null){
throw new RuntimeException("get transfer error -----");
}
return transfer;
}
private byte[] execPre(byte[] params)throws Exception{
try {
return getSessionTransfer().sendMsgAndRecv(params);
} catch (IOException e) {
e.printStackTrace();
if(e.getMessage().contains("pipe")){
closeSession();
return getSessionTransfer().sendMsgAndRecv(params);
}else {
throw e;
}
}
}
CallResult execNew(IReq method) throws Exception {
byte[] result = execPre(ParcelableUtil.marshall(new CallRequest(method)));
return ParcelableUtil.unmarshall(
result, CallResult.CREATOR);
}
void closeBgServer() {
try {
NormalCmd cmd = new NormalCmd(Types.CLOSE);
createSession().getTransfer().sendMsgAndRecv(ParcelableUtil.marshall(cmd));
} catch (Exception e) {
Log.w(TAG, "closeBgServer: "+e.getCause()+" "+e.getMessage());
}
}
private List<String> getCommonds() {
List<String> cmds = new ArrayList<>();
cmds.add("sh "+SH_FILE);
return cmds;
}
private boolean useRootStartServer() throws Exception {
DataOutputStream outputStream = null;
RootChecker checker = null;
Process exec = null;
try {
Log.e(TAG, "useRootStartServer --> ");
exec = Runtime.getRuntime().exec("su");
checker = new RootChecker(exec);
checker.start();
try {
checker.join(20000);
} catch (Exception e) {
e.printStackTrace();
}
if (checker.exit == -1) {
throw new RuntimeException("grant root timeout");
}
if (checker.exit != 1) {
throw new RuntimeException(checker.errorMsg);
}
outputStream = new DataOutputStream(exec.getOutputStream());
List<String> cmds = getCommonds();
writeCmds(cmds, outputStream);
SystemClock.sleep(3000);
return true;
} catch (Exception e) {
e.printStackTrace();
try {
if (exec != null) {
exec.destroy();
}
} catch (Exception e2) {
e2.printStackTrace();
}
if (checker != null) {
checker.interrupt();
}
throw e;
} finally {
try {
if (exec != null) {
//exec.destroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void writeCmds(List<String> cmds, OutputStream outputStream) throws IOException {
for (String cmd : cmds) {
outputStream.write((cmd + "\n").getBytes("UTF-8"));
outputStream.flush();
}
outputStream.flush();
}
private void startServer() throws Exception {
//重试10次
for (int i = 0; i < 10; i++) {
try {
if(useRootStartServer()){
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
Log.e(TAG, "startServer --> end ---");
}
private static class RootChecker extends Thread {
int exit = -1;
String errorMsg = null;
Process process;
private RootChecker(Process process) {
this.process = process;
}
@Override
public void run() {
try {
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(process.getInputStream(), "UTF-8"));
BufferedWriter outputStream = new BufferedWriter(
new OutputStreamWriter(this.process.getOutputStream(), "UTF-8"));
outputStream.write("echo U333L\n");
outputStream.flush();
while (true) {
String line = inputStream.readLine();
if (line == null) {
throw new EOFException();
}
if ("".equals(line)) {
continue;
}
if ("U333L".equals(line)) {
this.exit = 1;
break;
}
errorMsg = "unkown error occured.";
}
} catch (IOException e) {
exit = -42;
if (e.getMessage() != null) {
errorMsg = e.getMessage();
} else {
errorMsg = "RootAccess denied?.";
}
}
}
}
private ClientSession createSession() throws IOException {
if(isRunning()){
return mSession;
}
Socket socket = new Socket("127.0.0.1", ServerConfig.PORT);
socket.setSoTimeout(1000 * 60);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
OpsDataTransfer transfer = new OpsDataTransfer(os, is, false);
transfer.shakehands(ServerConfig.TOKEN, false);
return new ClientSession(transfer);
}
private static class ClientSession {
private volatile boolean isRunning = false;
private OpsDataTransfer transfer;
ClientSession(OpsDataTransfer transfer) {
this.transfer = transfer;
isRunning = true;
}
void close() {
isRunning = false;
if (transfer != null) {
transfer.stop();
}
transfer = null;
}
boolean isRunning() {
return isRunning && transfer != null;
}
OpsDataTransfer getTransfer() {
return transfer;
}
}
}
\ No newline at end of file
package com.xf.agent.wrap;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import java.io.File;
class SConfig {
static final String DIR_PREFIX="/sdcard/Android/data/com.xf.weixinclick";
static final String JAR_NAME = "agent.jar";
static final String SH_NAME = "agent.sh";
private static File destJarFile;
private static volatile boolean sInited = false;
static void init(Context context) {
if(sInited){
return;
}
destJarFile = new File(context.getExternalFilesDir(null).getParent(), JAR_NAME);
//sClassPath = destJarFile.getAbsolutePath();
AssetsUtils.copyFile(context, JAR_NAME, destJarFile,true);
File destFile = new File(context.getExternalFilesDir(null).getParentFile(), SH_NAME);
AssetsUtils.copyFile(context, SH_NAME, destFile,true);
sInited = true;
}
}
\ No newline at end of file
<resources>
<string name="app_name">agentlib</string>
</resources>
...@@ -16,27 +16,32 @@ android { ...@@ -16,27 +16,32 @@ android {
storePassword '123456' storePassword '123456'
} }
} }
compileSdkVersion 25 compileSdkVersion versions.compileSdkVersion
buildToolsVersion "26.0.2" buildToolsVersion versions.buildToolsVersion
defaultConfig { defaultConfig {
applicationId "com.xf.weixinclick" applicationId versions.applicationId
minSdkVersion 21 minSdkVersion versions.minSdkVersion
targetSdkVersion 25 targetSdkVersion versions.targetSdkVersion
versionCode 8 versionCode 8
versionName "1.5.4" versionName "1.5.5"
multiDexEnabled true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild { // externalNativeBuild {
cmake { // cmake {
cppFlags "" // cppFlags ""
} // }
} // }
//
ndk { ndk {
//选择要添加的对应cpu类型的.so库。 //选择要添加的对应cpu类型的.so库。
abiFilters 'armeabi', 'x86' abiFilters 'armeabi', 'x86'
} }
} }
lintOptions {
abortOnError false
}
buildTypes { buildTypes {
release { release {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
...@@ -47,6 +52,10 @@ android { ...@@ -47,6 +52,10 @@ android {
} }
} }
aaptOptions {
noCompress 'jar','sh'
}
sourceSets.main.jni.srcDirs = [] sourceSets.main.jni.srcDirs = []
//禁止自带的ndk功能 //禁止自带的ndk功能
sourceSets.main.jniLibs.srcDirs = ['src/main/libs', 'src/main/jniLibs'] sourceSets.main.jniLibs.srcDirs = ['src/main/libs', 'src/main/jniLibs']
...@@ -64,34 +73,39 @@ android { ...@@ -64,34 +73,39 @@ android {
} }
dependencies { dependencies {
def retrofitVersion = '2.1.0' implementation fileTree(include: ['*.jar'], dir: 'libs')
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.squareup.retrofit2:retrofit:$retrofitVersion" api project(":agentlib")
compile "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion" api project(":debugTools")
compile "com.squareup.retrofit2:converter-gson:$retrofitVersion" implementation "com.squareup.retrofit2:retrofit:$versions.retrofit"
compile "com.squareup.retrofit2:retrofit-mock:$retrofitVersion" implementation "com.squareup.retrofit2:adapter-rxjava:$versions.retrofit"
implementation "com.squareup.retrofit2:converter-gson:$versions.retrofit"
compile 'com.squareup.okhttp3:logging-interceptor:3.6.0' implementation "com.squareup.retrofit2:retrofit-mock:$versions.retrofit"
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.google.code.gson:gson:2.7' implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
compile 'com.github.bumptech.glide:glide:3.5.2' implementation 'io.reactivex:rxandroid:1.2.1'
compile 'org.greenrobot:eventbus:3.0.0' implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.github.bumptech.glide:glide:3.5.2'
compile 'com.android.support:appcompat-v7:25.3.1' implementation 'org.greenrobot:eventbus:3.1.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:design:25.3.1' implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.jakewharton:butterknife:8.2.1' implementation "com.android.support:appcompat-v7:$versions.supportLibVersion"
implementation "com.android.support:design:$versions.supportLibVersion"
implementation 'com.jakewharton:butterknife:8.2.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.2.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.2.1'
compile 'com.aliyun.ams:alicloud-android-push:3.0.11@aar' implementation 'com.aliyun.ams:alicloud-android-push:3.0.11@aar'
compile 'com.aliyun.ams:alicloud-android-utdid:1.1.5.3' implementation 'com.aliyun.ams:alicloud-android-utdid:1.1.5.3'
compile 'com.aliyun.ams:alicloud-android-ut:5.0.0' implementation 'com.aliyun.ams:alicloud-android-ut:5.0.0'
compile 'com.aliyun.ams:alicloud-android-third-push:3.0.3@aar' implementation 'com.aliyun.ams:alicloud-android-third-push:3.0.3@aar'
annotationProcessor "org.androidannotations:androidannotations:$AAVersion" annotationProcessor "org.androidannotations:androidannotations:$AAVersion"
}
repositories { annotationProcessor ("com.tinkerpatch.tinker:tinker-android-anno:1.9.2")
mavenCentral() implementation("com.tinkerpatch.sdk:tinkerpatch-android-sdk:1.2.2")
implementation "com.android.support:multidex:1.0.3"
} }
apply from: 'tinkerpatch.gradle'
package com.xf.secondndk;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.xf.secondndk", appContext.getPackageName());
}
}
...@@ -2,12 +2,14 @@ ...@@ -2,12 +2,14 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
package="com.xf.weixinclick"> package="com.xf.weixinclick">
<uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" /> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE" /> <uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"
tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
...@@ -19,7 +21,10 @@ ...@@ -19,7 +21,10 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions"/>
<uses-permission <uses-permission
android:name="android.permission.INJECT_EVENTS" android:name="android.permission.INJECT_EVENTS"
...@@ -45,6 +50,7 @@ ...@@ -45,6 +50,7 @@
</activity> </activity>
<activity android:name=".MainActivity" <activity android:name=".MainActivity"
android:windowSoftInputMode="adjustPan"/> android:windowSoftInputMode="adjustPan"/>
<activity android:name=".DebugActivity"/>
<!-- 消息接收监听器 (用户可自主扩展) --> <!-- 消息接收监听器 (用户可自主扩展) -->
<receiver <receiver
...@@ -63,7 +69,7 @@ ...@@ -63,7 +69,7 @@
<service <service
android:name=".NewService" android:name=".WXCService"
android:enabled="true" android:enabled="true"
android:exported="true" android:exported="true"
android:label="@string/app_name" android:label="@string/app_name"
......
package com.xf.weixinclick;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import com.xf.weixinclick.agent.AgentExecutor;
import com.xf.weixinclick.agent.AutoProcesser;
import com.xf.weixinclick.debugtool.LogcatTools;
import java.util.concurrent.Callable;
import rx.Single;
import rx.SingleSubscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class DebugActivity extends BaseActivity {
private static final String TAG = "DebugActivity";
@BindView(R.id.tv_logcat_url)
TextView tvLogcatUrl;
@BindView(R.id.btn_logcat)
Button btnSwitchLogcat;
@Override
int getContentView() {
return R.layout.activity_debug;
}
@Override
void initAction() {
updateStatus();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@OnClick(R.id.btn_logcat)
void onClickLogcat(View view){
if(LogcatTools.isRunning()){
LogcatTools.stopLogcat(this);
}else {
LogcatTools.startLogcat(this);
}
updateStatus();
}
@OnClick(R.id.btn_enable_accessibility)
void onClickAutoEnableAccessibility(View view){
AutoProcesser.enableAccessibility(this,null);
}
@OnClick(R.id.btn_restart_4g)
void onClickRestart4G(View view){
AgentExecutor.restartNetwork().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);
}
});
}
private void updateStatus(){
if(LogcatTools.isRunning()){
btnSwitchLogcat.setText("关闭logcat");
Single.fromCallable(new Callable<String>() {
@Override
public String call() throws Exception {
return LogcatTools.logcatHttpUrl();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleSubscriber<String>() {
@Override
public void onSuccess(String s) {
tvLogcatUrl.setText(s);
}
@Override
public void onError(Throwable error) {
}
});
}else {
btnSwitchLogcat.setText("开启logcat");
tvLogcatUrl.setText("off");
}
}
}
...@@ -63,7 +63,7 @@ public class HeartBeatAction { ...@@ -63,7 +63,7 @@ public class HeartBeatAction {
if (TextUtils.isEmpty(name)){ if (TextUtils.isEmpty(name)){
return; return;
} }
onWake();
HttpClientApi.heartBat(name, HttpClientApi.heartBat(name,
PushServiceFactory.getCloudPushService().getDeviceId(),getBattery()); PushServiceFactory.getCloudPushService().getDeviceId(),getBattery());
...@@ -77,4 +77,12 @@ public class HeartBeatAction { ...@@ -77,4 +77,12 @@ public class HeartBeatAction {
int capacity = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); int capacity = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
return capacity; return capacity;
} }
private void onWake(){
}
} }
package com.xf.weixinclick;
import android.accessibilityservice.AccessibilityService;
import android.view.accessibility.AccessibilityEvent;
import com.xf.weixinclick.core.Worker;
public class WXCService extends AccessibilityService {
private Worker worker = null;
@Override
public void onCreate() {
super.onCreate();
worker = Worker.getInstance();
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if(worker == null){
worker = Worker.getInstance();
}
worker.handleEvent(this,event);
}
@Override
public void onInterrupt() {
if(worker == null){
worker = Worker.getInstance();
}
worker.onInterrupt(this);
}
}
package com.xf.weixinclick.agent;
import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import com.xf.agent.common.CmdResult;
import com.xf.agent.wrap.AgentManager;
import com.xf.weixinclick.agent.auto.EnableAccessibility;
import com.xf.weixinclick.myApplication;
import java.util.concurrent.Callable;
import rx.Single;
import rx.SingleSubscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class AgentExecutor {
private static final String TAG = "AgentExecutor";
private static AgentManager agentManager;
public static void init(Context context){
if(agentManager == null){
agentManager = new AgentManager(context);
Rect rect = new Rect();
DisplayMetrics metric = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metric);
rect.set(0,0,metric.widthPixels,metric.heightPixels);
MotionRunner.get().setScreenRect(rect);
DebugTools.init(context);
}
}
public static Single<CmdResult> exec(final String cmd){
Log.e(TAG, "exec cmd --> "+cmd);
return Single.fromCallable(new Callable<CmdResult>() {
@Override
public CmdResult call() throws Exception {
try {
return agentManager.exeCommand(cmd);
} catch (Throwable throwable) {
throw new Exception(throwable);
}
}
}).subscribeOn(Schedulers.io());
}
public static CmdResult execNonReturn(final String cmd){
return exec(cmd).toBlocking().value();
}
public static Single<Boolean> restartNetwork(){
return Single.fromCallable(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
return agentManager.restart4G();
} catch (Throwable throwable) {
throw new Exception(throwable);
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
public static boolean isConnected(){
return agentManager.isRunning();
}
public static void preLoad(){
if(isConnected()){
return;
}
exec("id").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);
}
});
}
}
package com.xf.weixinclick.agent;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.xf.weixinclick.agent.auto.EnableAccessibility;
import com.xf.weixinclick.agent.auto.EnableUsageStats;
import com.xf.weixinclick.myApplication;
import rx.Single;
import rx.SingleSubscriber;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class AutoProcesser {
private static final String TAG = "AutoProcesser";
/**
* 自动开启辅助服务
* @param context
*/
public static void enableAccessibility(final Context context,final SingleSubscriber<Boolean> subscriber){
DebugTools.showAction("自动开启辅助服务中,请勿点击!");
Single.fromCallable(new EnableAccessibility(context.getApplicationContext()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(
new SingleSubscriber<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
DebugTools.dismiss();
Log.e(TAG, "onSuccess -->自动开启辅助服务 "+aBoolean);
Toast.makeText(context,"开启辅助服务 "+aBoolean,Toast.LENGTH_SHORT).show();
if(subscriber != null){
subscriber.onSuccess(aBoolean);
}
}
@Override
public void onError(Throwable error) {
DebugTools.dismiss();
Log.e(TAG, "onError --> ",error);
if(subscriber != null){
subscriber.onError(error);
}
}
});
}
public static void enableUsageStats(final Context context,final SingleSubscriber<Boolean> subscriber){
DebugTools.showAction("自动开启UsageStats,请勿点击!");
Single.fromCallable(new EnableUsageStats(context))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleSubscriber<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
Log.e(TAG, "onSuccess -->自动开启 UsageStats "+aBoolean);
DebugTools.dismiss();
}
@Override
public void onError(Throwable error) {
DebugTools.dismiss();
}
});
}
}
package com.xf.weixinclick.agent;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import com.xf.weixinclick.debugtool.LogcatTools;
import com.xf.weixinclick.myApplication;
import rx.android.schedulers.AndroidSchedulers;
public class DebugTools {
private static Handler sHandler = new Handler(Looper.getMainLooper());
private static TextView textView;
static void init(Context context){
//LogcatTools.startLogcat(context);
}
public static void showLog(String title){
Context context = myApplication.getInstence();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams lp = new LayoutParams();
lp.flags = LayoutParams.FLAG_NOT_FOCUSABLE |LayoutParams.FLAG_NOT_TOUCHABLE|LayoutParams.FLAG_NOT_TOUCH_MODAL;
lp.type = LayoutParams.TYPE_TOAST;
lp.gravity = Gravity.CENTER;
lp.format= PixelFormat.RGBA_8888;
lp.width = dip2px(200);
lp.height = dip2px(200);
textView = new TextView(context);
textView.setTextColor(Color.RED);
textView.setText(title);
textView.setTextSize(16);
//textView.setVerticalScrollBarEnabled(true);
windowManager.addView(textView,lp);
}
public static void log(final String msg){
// textView.post(new Runnable() {
// @Override
// public void run() {
// textView.append(msg);
// textView.append("\n");
//
//
// }
// });
}
public static void showAction(final String text){
Runnable runnable = new Runnable() {
@Override
public void run() {
Context context = myApplication.getInstence();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams lp = new LayoutParams();
lp.flags = LayoutParams.FLAG_NOT_FOCUSABLE |LayoutParams.FLAG_NOT_TOUCHABLE|LayoutParams.FLAG_NOT_TOUCH_MODAL;
lp.type = LayoutParams.TYPE_TOAST;
lp.gravity = Gravity.CENTER;
lp.format= PixelFormat.RGBA_8888;
lp.width = dip2px(200);
lp.height = dip2px(200);
textView = new TextView(context);
textView.setTextColor(Color.RED);
textView.setText(text);
textView.setTextSize(16);
//textView.setVerticalScrollBarEnabled(true);
windowManager.addView(textView,lp);
}
};
runOnMainThread(runnable);
}
public static void dismiss(){
Runnable runnable = new Runnable() {
@Override
public void run() {
Context context = myApplication.getInstence();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if(textView != null && textView.getParent() != null){
Log.e("test", "run --> dismiss ");
windowManager.removeView(textView);
}
textView = null;
}
};
runOnMainThread(runnable);
}
public static int dip2px(float dpValue) {
float scale = myApplication.getInstence().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5F);
}
private static void runOnMainThread(Runnable runnable){
if(Thread.currentThread() != Looper.getMainLooper().getThread()){
sHandler.post(runnable);
}else {
runnable.run();
}
}
}
package com.xf.weixinclick.agent;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat.FocusRealDirection;
import android.view.KeyEvent;
import android.view.View;
import com.xf.agent.common.CmdResult;
/**
* input 命令处理点击封装
*/
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 MotionRunner sInstance = null;
public static MotionRunner get(){
if(sInstance == null){
synchronized (MotionRunner.class){
if(sInstance == null){
sInstance = new MotionRunner();
}
}
}
return sInstance;
}
private Rect screenRect;
private MotionRunner(){
}
void setScreenRect(Rect screenRect) {
this.screenRect = screenRect;
}
/**
* 返回
*/
public void clickBack(){
sendKeyEvent(KeyEvent.KEYCODE_BACK);
}
/**
* Home键
*/
public void clickHome(){
sendKeyEvent(KeyEvent.KEYCODE_HOME);
}
/**
* 点击
* @param x
* @param y
*/
public boolean tap(int x,int y){
CmdResult cmdResult = AgentExecutor.execNonReturn(TAP_EVENT_CMD + x + " " + y);
return cmdResult!=null && cmdResult.code == 0;
}
/**
* 长按
* @param x
* @param y
* @param duration 时间 毫秒
*/
public void longPress(int x,int y,int duration){
StringBuilder cmd = new StringBuilder(SWIPE_EVENT_CMD);
cmd.append(x).append(' ')
.append(y).append(' ')
.append(x).append(' ')
.append(y).append(' ')
.append(duration);
AgentExecutor.execNonReturn(cmd.toString());
}
/**
* 滑动
* @param startX 起点
* @param startY
* @param endX 终点
* @param endY
* @param duration 滑动时长
*/
public void swipe(int startX,int startY,int endX,int endY,int duration){
StringBuilder cmd = new StringBuilder(SWIPE_EVENT_CMD);
cmd.append(startX).append(' ')
.append(startY).append(' ')
.append(endX).append(' ')
.append(endY).append(' ')
.append(duration);
AgentExecutor.execNonReturn(cmd.toString());
}
/**
* 滑动
* @param startX
* @param startY
* @param direction 方向 {@see View.FOCUS_LEFT}
* @param distance 滑动距离px
* @param duration
*/
public void swipeTo(int startX,int startY,@FocusRealDirection int direction,int distance,int duration){
int endX=startX,endY=startY;
switch (direction){
case View.FOCUS_UP:
endY-=distance;
break;
case View.FOCUS_DOWN:
endY+=distance;
break;
case View.FOCUS_LEFT:
endX-=distance;
break;
case View.FOCUS_RIGHT:
endY+=distance;
break;
}
swipe(startX,startY,endX,endY,duration);
}
public void scrollUp(int distance){
swipeTo(screenRect.centerX(),screenRect.centerY(),View.FOCUS_DOWN,distance,300);
}
public void scrollDown(int distance){
swipeTo(screenRect.centerX(),screenRect.centerY(),View.FOCUS_UP,distance,300);
}
private void sendKeyEvent(int code){
AgentExecutor.execNonReturn(KEY_EVENT_CMD+code);
}
}
package com.xf.weixinclick.agent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import com.xf.agent.common.CmdResult;
import com.xf.weixinclick.agent.uiautomator.BasicTreeNode;
import com.xf.weixinclick.agent.uiautomator.UiHierarchyXmlLoader;
import com.xf.weixinclick.agent.uiautomator.UiNode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import rx.Single;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class UiHierarchyFinder {
private static final String TAG = "UiHierarchyFinder";
private static final String DEF_FILE_PATH = "/sdcard/window_dump.xml";
private static final String CMD = "uiautomator dump";
private BasicTreeNode basicTreeNode;
public void dump() {
CmdResult value = AgentExecutor.exec(CMD).toBlocking().value();
Log.e(TAG, "dump --> "+value);
if(value == null || value.code != 0){
throw new RuntimeException("dump ERROR !!!");
}
}
public List<UiNode> dumpAndFindByName(final String text) {
if (basicTreeNode == null) {
dump();
parseDefault();
}
return findNodeByText(text);
}
public Single<List<UiNode>> dumpAndFindByNameAsync(final String text) {
return Single.fromCallable(new Callable<List<UiNode>>() {
@Override
public List<UiNode> call() throws Exception {
if (basicTreeNode == null) {
dump();
parseDefault();
}
return findNodeByText(text);
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
public void parseDefault() {
UiHierarchyXmlLoader loader = new UiHierarchyXmlLoader();
basicTreeNode = loader.parseXml(DEF_FILE_PATH);
}
public void parse(String xmlPath) {
UiHierarchyXmlLoader loader = new UiHierarchyXmlLoader();
basicTreeNode = loader.parseXml(xmlPath);
}
public void printNodes() {
if(basicTreeNode == null){
parseDefault();
}
printNodes(basicTreeNode.getChildren());
}
public @NonNull
List<UiNode> findNodeByText(String text) {
List<UiNode> ret = new ArrayList<>();
findByAttr(basicTreeNode.getChildren(), "text", text, ret);
return ret;
}
public @NonNull
List<UiNode> findNodeById(String id) {
List<UiNode> ret = new ArrayList<>();
findByAttr(basicTreeNode.getChildren(), "resource-id", id, ret);
return ret;
}
private void findByAttr(BasicTreeNode[] nodes, String key, String value, List<UiNode> ret) {
if (nodes != null) {
for (BasicTreeNode node : nodes) {
if (node.hasChild()) {
findByAttr(node.getChildren(), key, value, ret);
} else {
if (node instanceof UiNode) {
String text = ((UiNode) node).getAttribute(key);
if (ret != null && TextUtils.equals(text, value)) {
ret.add(((UiNode) node));
}
}
}
}
}
}
private void printNodes(BasicTreeNode[] nodes) {
if (nodes != null) {
for (BasicTreeNode node : nodes) {
if (node.hasChild()) {
printNodes(node.getChildren());
} else {
if (node instanceof UiNode) {
String text = ((UiNode) node).getAttribute("text");
if (!TextUtils.isEmpty(text)) {
Log.e(TAG, "printNodes --> " + text);
}
}
}
}
}
}
}
package com.xf.weixinclick.agent.auto;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.SystemClock;
import android.util.Log;
import com.xf.weixinclick.agent.DebugTools;
import com.xf.weixinclick.agent.MotionRunner;
import com.xf.weixinclick.agent.UiHierarchyFinder;
import com.xf.weixinclick.agent.uiautomator.UiNode;
import java.util.List;
import java.util.concurrent.Callable;
/**
* 自动开启辅助服务
*/
public class EnableAccessibility implements Callable<Boolean> {
private static final String TAG = "EnableAccessibility";
private Context context;
public EnableAccessibility(Context context) {
this.context = context;
}
@Override
public Boolean call() throws Exception {
DebugTools.log("exec --> 启动act");
Log.e(TAG, "exec --> 启动act");
startAct();
SystemClock.sleep(2000);
DebugTools.log("exec --> 滑动 到底部");
Log.e(TAG, "exec --> 滑动 到底部");
MotionRunner.get().scrollDown(500);
SystemClock.sleep(1000);
MotionRunner.get().scrollDown(800);
SystemClock.sleep(1000);
MotionRunner.get().scrollDown(800);
SystemClock.sleep(1000);
// MotionRunner.get().scrollDown(800);
// SystemClock.sleep(1000);
Log.e(TAG, "exec --> 滑动 结束,搜索[无障碍]");
UiHierarchyFinder finder = new UiHierarchyFinder();
List<UiNode> nodes = finder.dumpAndFindByName("无障碍");
Log.e(TAG, "找到"+nodes.size()+"个节点");
if(nodes.isEmpty()){
DebugTools.log("没有在[设置]-[辅助功能]中找到 [无障碍]选项 !");
throw new RuntimeException("没有在[设置]-[辅助功能]中找到 [无障碍]选项 !");
}else {
//点击无障碍
Rect bounds = nodes.get(0).getBounds();
DebugTools.log("点击第0个节点的位置"+bounds);
MotionRunner.get().tap(bounds.centerX(),bounds.centerY());
SystemClock.sleep(1000);
//打开了无障碍页面
//搜索家粉
DebugTools.log("跳转到无障碍服务列表页面,开始搜索[家粉]");
finder = new UiHierarchyFinder();
nodes = finder.dumpAndFindByName("家粉");
if(nodes.isEmpty()){
throw new RuntimeException("没有在[无障碍]页面找到[家粉] 的辅助服务!");
}else {
//找到了家粉 点击
bounds = nodes.get(0).getBounds();
MotionRunner.get().tap(bounds.centerX(),bounds.centerY());
SystemClock.sleep(2000);
//如果正常 进入家粉辅助服务详情页面
//判断是否跳转成功了,搜索辅助服务的描述
finder = new UiHierarchyFinder();
nodes = finder.dumpAndFindByName("微信点击辅助服务");
if(nodes.isEmpty()){
throw new RuntimeException(" 没有正常打开 辅助服务详情 界面 !");
}else {
nodes = finder.findNodeByText("家粉");
if(nodes.isEmpty() || nodes.size() <= 1){
throw new RuntimeException(" 没有正常打开 [辅助服务详情] 界面 !");
}else {
//此处有两个节点,标题和点击项
Log.e(TAG, "call --> "+nodes);
bounds = nodes.get(0).getBounds();
//点击,显示弹窗
MotionRunner.get().tap(bounds.centerX(),bounds.centerY());
SystemClock.sleep(2000);
//点击确定按钮
MotionRunner.get().tap(470,870);
SystemClock.sleep(1500);
//然后返回
MotionRunner.get().clickBack();
SystemClock.sleep(1500);
MotionRunner.get().clickBack();
SystemClock.sleep(1500);
MotionRunner.get().clickBack();
SystemClock.sleep(1500);
return true;
}
}
}
}
}
private void startAct(){
Intent intent2 = new Intent(
android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
package com.xf.weixinclick.agent.auto;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
import java.util.concurrent.Callable;
/**
* 自动开启UsageStatsManager
*/
public class EnableUsageStats implements Callable<Boolean> {
private static final String TAG = "EnableUsageStats";
private Context context;
public EnableUsageStats(Context context) {
this.context = context;
}
@Override
public Boolean call() throws Exception {
Log.e(TAG, "exec --> 启动act");
startAct();
SystemClock.sleep(2000);
return true;
}
private void startAct(){
Intent intent2 = new Intent(
android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS);
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xf.weixinclick.agent.uiautomator;
public class AttributePair {
public String key, value;
public AttributePair(String key, String value) {
this.key = key;
this.value = value;
}
}
\ No newline at end of file
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xf.weixinclick.agent.uiautomator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BasicTreeNode {
private static final BasicTreeNode[] CHILDREN_TEMPLATE = new BasicTreeNode[]{};
protected BasicTreeNode mParent;
protected final List<BasicTreeNode> mChildren = new ArrayList<BasicTreeNode>();
public int x, y, width, height;
// whether the boundary fields are applicable for the node or not
// RootWindowNode has no bounds, but UiNodes should
protected boolean mHasBounds = false;
public void addChild(BasicTreeNode child) {
if (child == null) {
throw new NullPointerException("Cannot add null child");
}
if (mChildren.contains(child)) {
throw new IllegalArgumentException("node already a child");
}
mChildren.add(child);
child.mParent = this;
}
public List<BasicTreeNode> getChildrenList() {
return Collections.unmodifiableList(mChildren);
}
public BasicTreeNode[] getChildren() {
return mChildren.toArray(CHILDREN_TEMPLATE);
}
public BasicTreeNode getParent() {
return mParent;
}
public boolean hasChild() {
return mChildren.size() != 0;
}
public int getChildCount() {
return mChildren.size();
}
public void clearAllChildren() {
for (BasicTreeNode child : mChildren) {
child.clearAllChildren();
}
mChildren.clear();
}
/**
* Find nodes in the tree containing the coordinate
*
* The found node should have bounds covering the coordinate, and none of its children's
* bounds covers it. Depending on the layout, some app may have multiple nodes matching it,
* the caller must provide a {@link IFindNodeListener} to receive all found nodes
*/
public boolean findLeafMostNodesAtPoint(int px, int py, IFindNodeListener listener) {
boolean foundInChild = false;
for (BasicTreeNode node : mChildren) {
foundInChild |= node.findLeafMostNodesAtPoint(px, py, listener);
}
// checked all children, if at least one child covers the point, return directly
if (foundInChild) {
return true;
}
// check self if the node has no children, or no child nodes covers the point
if (mHasBounds) {
if (x <= px && px <= x + width && y <= py && py <= y + height) {
listener.onFoundNode(this);
return true;
} else {
return false;
}
} else {
return false;
}
}
public Object[] getAttributesArray() {
return null;
}
;
public static interface IFindNodeListener {
void onFoundNode(BasicTreeNode node);
}
}
\ No newline at end of file
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xf.weixinclick.agent.uiautomator;
public class RootWindowNode extends BasicTreeNode {
private final String mWindowName;
private Object[] mCachedAttributesArray;
public RootWindowNode(String windowName) {
mWindowName = windowName;
}
@Override
public String toString() {
return mWindowName;
}
@Override
public Object[] getAttributesArray() {
if (mCachedAttributesArray == null) {
mCachedAttributesArray = new Object[]{new AttributePair("window-name", mWindowName)};
}
return mCachedAttributesArray;
}
}
\ No newline at end of file
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xf.weixinclick.agent.uiautomator;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
//https://android.googlesource.com/platform/frameworks/testing/+/aecdc4a/uiautomator/utils/uiautomatorviewer/src/com/android/uiautomator/tree
public class UiHierarchyXmlLoader {
private BasicTreeNode mRootNode;
public UiHierarchyXmlLoader() {
}
/**
* Uses a SAX parser to process XML dump
*/
public BasicTreeNode parseXml(String xmlPath) {
mRootNode = null;
// standard boilerplate to get a SAX parser
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = null;
try {
parser = factory.newSAXParser();
} catch (ParserConfigurationException e) {
e.printStackTrace();
return null;
} catch (SAXException e) {
e.printStackTrace();
return null;
}
// handler class for SAX parser to receiver standard parsing events:
// e.g. on reading "<foo>", startElement is called, on reading "</foo>",
// endElement is called
DefaultHandler handler = new DefaultHandler() {
BasicTreeNode mParentNode;
BasicTreeNode mWorkingNode;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
boolean nodeCreated = false;
// starting an element implies that the element that has not yet been closed
// will be the parent of the element that is being started here
mParentNode = mWorkingNode;
if ("hierarchy".equals(qName)) {
mWorkingNode = new RootWindowNode(attributes.getValue("windowName"));
nodeCreated = true;
} else if ("node".equals(qName)) {
UiNode tmpNode = new UiNode();
for (int i = 0; i < attributes.getLength(); i++) {
tmpNode.addAtrribute(attributes.getQName(i), attributes.getValue(i));
}
mWorkingNode = tmpNode;
nodeCreated = true;
}
// nodeCreated will be false if the element started is neither
// "hierarchy" nor "node"
if (nodeCreated) {
if (mRootNode == null) {
// this will only happen once
mRootNode = mWorkingNode;
}
if (mParentNode != null) {
mParentNode.addChild(mWorkingNode);
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
//mParentNode should never be null here in a well formed XML
if (mParentNode != null) {
// closing an element implies that we are back to working on
// the parent node of the element just closed, i.e. continue to
// parse more child nodes
mWorkingNode = mParentNode;
mParentNode = mParentNode.getParent();
}
}
};
try {
parser.parse(new File(xmlPath), handler);
} catch (SAXException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return mRootNode;
}
}
\ No newline at end of file
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xf.weixinclick.agent.uiautomator;
import android.graphics.Rect;
import android.text.TextUtils;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UiNode extends BasicTreeNode {
private static final Pattern BOUNDS_PATTERN = Pattern
.compile("\\[-?(\\d+),-?(\\d+)\\]\\[-?(\\d+),-?(\\d+)\\]");
// use LinkedHashMap to preserve the order of the attributes
private final Map<String, String> mAttributes = new LinkedHashMap<String, String>();
private String mDisplayName = "ShouldNotSeeMe";
private Object[] mCachedAttributesArray;
public void addAtrribute(String key, String value) {
mAttributes.put(key, value);
updateDisplayName();
if ("bounds".equals(key)) {
updateBounds(value);
}
}
public Map<String, String> getAttributes() {
return Collections.unmodifiableMap(mAttributes);
}
/**
* Builds the display name based on attributes of the node
*/
private void updateDisplayName() {
String className = mAttributes.get("class");
if (className == null)
return;
String text = mAttributes.get("text");
if (text == null)
return;
String contentDescription = mAttributes.get("content-desc");
if (contentDescription == null)
return;
String index = mAttributes.get("index");
if (index == null)
return;
String bounds = mAttributes.get("bounds");
if (bounds == null) {
return;
}
// shorten the standard class names, otherwise it takes up too much space on UI
className = className.replace("android.widget.", "");
className = className.replace("android.view.", "");
StringBuilder builder = new StringBuilder();
builder.append('(');
builder.append(index);
builder.append(") ");
builder.append(className);
if (!text.isEmpty()) {
builder.append(':');
builder.append(text);
}
if (!contentDescription.isEmpty()) {
builder.append(" {");
builder.append(contentDescription);
builder.append('}');
}
builder.append(' ');
builder.append(bounds);
mDisplayName = builder.toString();
}
private void updateBounds(String bounds) {
Matcher m = BOUNDS_PATTERN.matcher(bounds);
if (m.matches()) {
x = Integer.parseInt(m.group(1));
y = Integer.parseInt(m.group(2));
width = Integer.parseInt(m.group(3)) - x;
height = Integer.parseInt(m.group(4)) - y;
mHasBounds = true;
} else {
throw new RuntimeException("Invalid bounds: " + bounds);
}
}
@Override
public String toString() {
return mDisplayName;
}
public String getAttribute(String key) {
return mAttributes.get(key);
}
public String getClassName(){
return getAttribute("class");
}
public String getPackageName(){
return getAttribute("package");
}
public boolean clickable(){
return TextUtils.equals(getAttribute("clickable"),"true");
}
public Rect getBounds(){
Rect rect = new Rect(x,y,x+width,y+height);
return rect;
}
public void getBounds(Rect rect){
rect.set(x,y,x+width,y+height);
}
@Override
public Object[] getAttributesArray() {
// this approach means we do not handle the situation where an attribute is added
// after this function is first called. This is currently not a concern because the
// tree is supposed to be readonly
if (mCachedAttributesArray == null) {
mCachedAttributesArray = new Object[mAttributes.size()];
int i = 0;
for (String attr : mAttributes.keySet()) {
mCachedAttributesArray[i++] = new AttributePair(attr, mAttributes.get(attr));
}
}
return mCachedAttributesArray;
}
}
\ No newline at end of file
package com.xf.weixinclick.core;
/**
* 创建日期:2018/4/17 on 13:58
* 描述:
* 作者:Li
*/
public class Cmder {
}
package com.xf.weixinclick.core;
import android.content.Context;
import com.xf.weixinclick.NewService;
import com.xf.weixinclick.agent.AutoProcesser;
import com.xf.weixinclick.bean.msg.ReceiverMsg;
import com.xf.weixinclick.utils.Accessibilitys;
import org.greenrobot.eventbus.EventBus;
import rx.SingleSubscriber;
public class MsgSender {
private static final String TAG = "MsgSender";
public static void checkAndSend(Context context,final ReceiverMsg msg){
//辅助服务开启并且可以收到消息
if(Accessibilitys.isSettingsOn(context) && EventBus.getDefault().hasSubscriberForEvent(ReceiverMsg.class) ){
EventBus.getDefault().post(msg);
}else {
//没有开启,先打开
AutoProcesser.enableAccessibility(context, new SingleSubscriber<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
if(aBoolean){
EventBus.getDefault().post(msg);
}else {
NewService.logToastAndUpload(TAG, "auto open AccessibilityService fail?");
}
}
@Override
public void onError(Throwable error) {
NewService.logToastAndUpload(TAG, "auto open AccessibilityService error:"+error.getMessage());
}
});
}
}
}
package com.xf.weixinclick.core;
/**
* 创建日期:2018/4/17 on 11:36
* 描述:
* 作者:Li
*/
public class TaskSession2 {
}
package com.xf.weixinclick.core;
final class WXIdsConfig {
private static final String ID_PREFIX = "com.tencent.mm:id/";
//不同版本id可能不同,根据后台配置更新
public static final String TV_HOME_WX = ID_PREFIX+"ca5"; //底部导航文件,根据 微信 匹配
public static final String HOME_MSG_TITLE = ID_PREFIX+"apx"; //文件传输助手,有多个,再根据文本匹配
public static final String BTN_CHANGE_INPUT =ID_PREFIX+"aaa"; //却换输入文字,匹配 切换到键盘
public static final String ET_INPUT_MSG = ID_PREFIX+"aac"; //聊天页面输入框
public static final String BTN_SEND_MSG = ID_PREFIX+"aai"; //聊天页面发送按钮
public static final String ITEM_MSG_CARD = ID_PREFIX+"jj"; //聊天页面消息卡片
public static final String BTN_SCAN_QR = ID_PREFIX+"ga"; //识别二维码
}
package com.xf.weixinclick.core;
final class WXIdsConfig {
private static final String ID_PREFIX = "com.tencent.mm:id/";
//不同版本id可能不同,根据后台配置更新
public static final String TV_HOME_WX = ID_PREFIX+"ca5"; //底部导航文件,根据 微信 匹配
public static final String HOME_MSG_TITLE = ID_PREFIX+"apx"; //文件传输助手,有多个,再根据文本匹配
public static final String BTN_CHANGE_INPUT =ID_PREFIX+"aaa"; //却换输入文字,匹配 切换到键盘
public static final String ET_INPUT_MSG = ID_PREFIX+"aac"; //聊天页面输入框
public static final String BTN_SEND_MSG = ID_PREFIX+"aai"; //聊天页面发送按钮
public static final String ITEM_MSG_CARD = ID_PREFIX+"jj"; //聊天页面消息卡片
public static final String BTN_SCAN_QR = ID_PREFIX+"ga"; //识别二维码
}
package com.xf.weixinclick.core;
import android.accessibilityservice.AccessibilityService;
import android.support.annotation.Keep;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import com.xf.weixinclick.bean.msg.ReceiverMsg;
import com.xf.weixinclick.core.TaskSession.TaskCallback;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
/**
* 收到任务消息 --> 加入队列 --> 启动执行 --> 检测运行环境(开启辅助服务,打开微信首页等)
*
* --> 依次点击(并检查点击结果) --> 返回并且执行结果上报 --> 继续下一个消息或者
*/
public class Worker {
private static final String LINE_SEP = System.getProperty("line.separator");
private static final String TAG = "Worker";
private static Worker sWorker = null;
public static Worker getInstance() {
if (sWorker == null) {
synchronized (Worker.class) {
if (sWorker == null) {
sWorker = new Worker();
}
}
}
return sWorker;
}
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private TaskSession currentTaskSession;
private LinkedBlockingQueue<ReceiverMsg> msgQueue = new LinkedBlockingQueue<>();
private Worker() {
EventBus.getDefault().register(this);
startQueue();
}
private void startQueue(){
new Thread(new Runnable() {
@Override
public void run() {
boolean run = true;
while (run) {
try {
if (!msgQueue.isEmpty()) {
ReceiverMsg msg = msgQueue.poll();
Log.e(TAG, "run --> 读取下一个消息");
startSession(msg);
taskWait();
Log.e(TAG, "run --> " + msg.getUnique_id() + " 结束"+LINE_SEP);
}
} catch (Exception e) {
e.printStackTrace();
run = false;
}
}
}
}).start();
}
public void handleEvent(AccessibilityService service, AccessibilityEvent event) {
if (currentTaskSession != null && currentTaskSession.canHandle()) {
currentTaskSession.handleEvent(service, event);
} else {
Log.e(TAG, "handleEvent --> 当前不需要处理"+LINE_SEP);
}
}
public void onInterrupt(AccessibilityService service) {
stopSession();
}
@Keep
@Subscribe
public void receiverMsg(final ReceiverMsg msg) {
Log.e(TAG, "receiverMsg --> 收到消息");
msgQueue.add(msg);
}
private void taskWait() {
try {
lock.lock();
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
private void taskOver() {
try {
lock.lock();
condition.signal();
} finally {
lock.unlock();
}
}
private void startSession(ReceiverMsg msg) {
Log.e(TAG, "startSession --> "+LINE_SEP);
currentTaskSession = new TaskSession(msg, new TaskCallback() {
@Override
public void onSuccess() {
Log.e(TAG, "onSuccess --> "+LINE_SEP);
taskOver();
}
@Override
public void onError(String msg) {
Log.e(TAG, "onError --> " + msg+LINE_SEP);
taskOver();
}
});
currentTaskSession.start();
}
public void stopSession() {
Log.e(TAG, "stopSession --> " );
taskOver();
if (currentTaskSession != null) {
currentTaskSession.end();
}
currentTaskSession = null;
}
public void clearAllMessage(){
msgQueue.clear();
}
}
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