又到年底了,微信群的红包又多起来了,但是每次总是不及他人手速快。网上有很多关于微信自动抢红包的 Android 源码,但是很多都已经没办法使用了。所以我们需要在那基础上重新编写代码,得以绕过微信的机制,从而抢到红包。最新版微信 7.0 好像已经没办法使用这个抢红包方法了,年会错失几个亿呀。后续再研究。
原理
我们使用的还是安卓自带的辅助功能 AccessibilityService 。
先来讲述以下原理,原理很简单,当页面发生变化的时候,搜索屏幕中的关键字,搜索到了就点开。这个原理在微信旧版本的自动抢红包是有效的,但是在新版本中,开红包的界面没办法这么做了,那我们需要自己模拟点击动作,从而点开这个红包。
AccessibilityService 在 SDK24 (即Android 7.0) 引入了一个方法 dispatchGesture ,从而使我们可以不用 root 就能模拟点击动作。所以在 app/build.gradle 中我们将最小的 SDK 版本设置为 24( minSdkVersion 24),所以如果你的安卓手机系统小于安卓 7.0,那就没办法使用我这个抢红包方法了。
onAccessibilityEvent
在辅助功能里面开启服务之后,onAccessibilityEvent 会接受到一些事件。
public void onAccessibilityEvent(AccessibilityEvent event) {
}
通过 event.getEventType() 就能获得当前界面的事件是什么。常用的事件如下。
事件 | 作用 |
---|---|
TYPES_ALL_MASK | 所有事件 |
TYPE_NOTIFICATION_STATE_CHANGED | 通知栏事件 |
TYPE_VIEW_CLICKED | 点击事件 |
TYPE_VIEW_FOCUSED | 获取焦点事件 |
TYPE_VIEW_LONG_CLICKED | 长按事件 |
TYPE_VIEW_SCROLLED | 页面变动事件 |
TYPE_VIEW_SELECTED | 控件选中 |
TYPE_VIEW_TEXT_CHANGED | 输入框文本改变 |
TYPE_VIEW_TEXT_SELECTION_CHANGED | 输入框文本 selection 改变 |
TYPE_WINDOW_CONTENT_CHANGED | 窗口内容改变 |
TYPE_WINDOW_STATE_CHANGED | 窗口状态改变 |
所以我们用到的其中的四个 TYPE_NOTIFICATION_STATE_CHANGED、TYPE_WINDOW_STATE_CHANGED、TYPE_VIEW_SCROLLED、TYPE_WINDOW_CONTENT_CHANGED。
创建 Service
package sms.example.com.automatic.service;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.app.Notification;
import android.app.PendingIntent;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Handler;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;
import java.util.List;
import sms.example.com.automatic.utils.ScreenUtils;
public class WeChetService extends AccessibilityService {
private static final String TAG = "WeChetService";
private static final String ENVELOPE_TEXT_KEY = "[微信红包]";
private static final String WECHET_PACKAGE_NAME = "com.tencent.mm";
private static final String WECHET_LAUCHER = "com.tencent.mm.ui.LauncherUI";
private static final String LUCKEY_MONEY_RECEIVER = "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyReceiveUI";
private static final String LUCKEY_MONEY_DETAIL = "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI";
private Handler handler = new Handler();
private CharSequence mClassName = "";
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
final int eventType = event.getEventType();
switch (eventType) {
case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
List<CharSequence> texts = event.getText();
if (!texts.isEmpty()) {
for (CharSequence t : texts) {
String text = String.valueOf(t);
Log.d(TAG, "监控微信消息==" + text);
if (text.contains(ENVELOPE_TEXT_KEY)) {
openNotification(event);
break;
}
}
}
break;
case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
openEnvelope(event);
break;
case AccessibilityEvent.TYPE_VIEW_SCROLLED:
case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
openEnvelopeContent(event);
break;
default:
break;
}
}
/**
* 打开通知栏
* @param event
*/
private void openNotification(AccessibilityEvent event) {
if (event.getParcelableData() == null || !(event.getParcelableData() instanceof Notification)) {
return;
}
Notification notification = (Notification) event.getParcelableData();
PendingIntent pendingIntent = notification.contentIntent;
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
}
private void openEnvelope(AccessibilityEvent event) {
CharSequence className = event.getClassName();
CharSequence packageName = event.getPackageName();
boolean isWechetPage = WECHET_PACKAGE_NAME.equals(packageName);
if(!isWechetPage) {
return;
}
if (className.toString().contains(WECHET_PACKAGE_NAME)) {
mClassName = className;
}
Log.i("openEnvelope", event.getClassName() + "");
if (WECHET_LAUCHER.equals(className)) {
findRedPacket();
} else if (LUCKEY_MONEY_RECEIVER.equals(className)) {
openRedPacket();
} else if (LUCKEY_MONEY_DETAIL.equals(className)) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
clickBackKey();
}
}, 300);
// Toast.makeText(this, "红包已经抢完--------", Toast.LENGTH_SHORT).show();
}
}
private void openEnvelopeContent(AccessibilityEvent event) {
Log.i("openEnvelopeContent", mClassName + "");
if (mClassName.equals(WECHET_LAUCHER)) {
findRedPacket();
}
}
/**
* 寻找领取红包关键字,找到之后点击打开
*/
private void findRedPacket() {
AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
if (nodeInfo == null) {
return;
}
List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText("领取红包");
if (list.isEmpty()) {
return;
}
for (AccessibilityNodeInfo info : list) {
AccessibilityNodeInfo parent = info.getParent();
if (parent != null) {
parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
break;
}
}
}
/**
* 打开红包,加延时是因为红包界面出现会有延时
* x 表示开字相对屏幕所在的横坐标, y 表示开字相对屏幕所在的纵坐标,不同手机会有不一样
*/
private void openRedPacket() {
final int x = ScreenUtils.getWindowsWidth(WeChetService.this) / 2;
final int y = 1200;
handler.postDelayed(new Runnable() {
@Override
public void run() {
dispatchGestureView(x, y);
}
}, 300);
}
/**
* 模拟点击事件
* @param x 横坐标
* @param y 纵坐标
*/
private void dispatchGestureView(int x, int y) {
Point position = new Point(x, y);
GestureDescription.Builder builder = new GestureDescription.Builder();
Path p = new Path();
p.moveTo(position.x, position.y);
builder.addStroke(new GestureDescription.StrokeDescription(p, 0L, 500L));
GestureDescription gesture = builder.build();
dispatchGesture(gesture, new GestureResultCallback() {
@Override
public void onCompleted(GestureDescription gestureDescription) {
super.onCompleted(gestureDescription);
Log.d(TAG, "onCompleted: 完成..........");
}
@Override
public void onCancelled(GestureDescription gestureDescription) {
super.onCancelled(gestureDescription);
Log.d(TAG, "onCompleted: 取消..........");
}
}, null);
}
@Override
public void onInterrupt() {
Toast.makeText(this, "微信抢红包服务已关闭", Toast.LENGTH_SHORT).show();
}
@Override
protected void onServiceConnected() {
super.onServiceConnected();
Toast.makeText(this, "微信抢红包服务已开启", Toast.LENGTH_SHORT).show();
}
/**
* 模拟返回键
*/
private void clickBackKey() {
performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
ScreenUtils
package sms.example.com.automatic.utils;
import android.app.Activity;
import android.content.Context;
import android.view.WindowManager;
public class ScreenUtils {
/**
* 获得屏幕的宽度
* @param context
* @return
*/
public static int getWindowsWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}
/**
* 获得屏幕的高度
*/
public static int getWindowsHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
}
创建对应的 xml
res/xml/text_server_config.xml
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagDefault"
android:canRetrieveWindowContent="true"
android:description="@string/accessibility_description"
android:notificationTimeout="10"
android:canPerformGestures="true">
</accessibility-service>
上面的属性 description 是在手机系统无障碍中显示的内容。
res/values/strings.xml
<resources>
<string name="app_name">抢红包</string>
<string name="accessibility_description">自助抢红包</string>
</resources>
AndroidManifest.xml 注册
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="sms.example.com.automatic">
<application
android:name=".application.app"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".service.WeChetService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:label="@string/accessibility_description">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/text_server_config"/>
</service>
</application>
</manifest>
判断服务是否开启
public static boolean isStartAccessibilityService(Context context, String name) {
AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
List<AccessibilityServiceInfo> serviceInfos = am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC);
for (AccessibilityServiceInfo info : serviceInfos) {
String id = info.getId();
if (id.contains(name)) {
return true;
}
}
return false;
}
private void isWeChetServiceOpen() {
String weChetServiceName = ".service.WeChetService";
boolean isWeChetServiceOpen = isStartAccessibilityService(this, weChetServiceName);
if (isWeChetServiceOpen) {
} else {
}
}
开启服务
private void jumpToSettingPage() {
Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
startActivity(intent);
}