抢红包,先看效果图~
实现自动抢红包,解决问题有两点:
一:如何实时监听发红包的事件
二:如何在红包到来的时候自动进入页面并自动点击红包
一、如何获取红包到来的事件
为了获取红包到来状态栏的变化,我们要用到一个类:Accessibility
许多AndroID使用者因为各种情况导致他们要以不同的方式与手机交互。
这包括了有些用户由于视力上,身体上,年龄上的问题致使他们不能看完整的屏幕或者使用触屏,也包括了无法很好接收到语音信息和提示的听力能力比较弱的用户。
AndroID提供了Accessibility功能和服务帮助这些用户更加简单地 *** 作设备,包括文字转语音(这个不支持中文),触觉反馈,手势 *** 作,轨迹球和手柄 *** 作。
OK,了解到这一点,那么接下来就顺利点了,首先来看看Accessibility以及AccessibilityService的使用
1.新建一个类继承AccessibilityService,并在AndroIDManifest文件里注册它:
<uses-permission androID:name="androID.permission.BIND_ACCESSIBIliTY_SERVICE" /> <application> <service androID:name="com.zkhb.weixinqinghongbao.service.QiangHongBaoService" androID:label="@string/app_name" androID:permission="androID.permission.BIND_ACCESSIBIliTY_SERVICE" > <intent-filter> <action androID:name="androID.accessibilityservice.AccessibilityService" /> </intent-filter> <Meta-data androID:name="androID.accessibilityservice" androID:resource="@xml/qianghongbao_service_config" /> </service></application>
在子类QiangHongBaoService里实现几个重要的重载方法:
onServiceConnected() - 可选。系统会在成功连接上你的服务的时候调用这个方法,在这个方法里你可以做一下初始化工作,例如设备的声音震动管理,也可以调用setServiceInfo()进行配置工作。
onAccessibilityEvent() - 必须。通过这个函数可以接收系统发送来的AccessibilityEvent,接收来的AccessibilityEvent是经过过滤的,过滤是在配置工作时设置的。
onInterrupt() - 必须。这个在系统想要中断AccessibilityService返给的响应时会调用。在整个生命周期里会被调用多次。
onUnbind() - 可选。在系统将要关闭这个AccessibilityService会被调用。在这个方法中进行一些释放资源的工作。
然后在/res/xml/accessibility_service_config.xml:
<accessibility-service xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:accessibilityEventTypes="typeNotificationStateChanged|typewindowstateChanged|typeWindowContentChanged" androID:accessibilityFeedbackType="FeedbackGeneric" androID:accessibilityFlags="" androID:canRetrIEveWindowContent="true" androID:description="@string/accessibility_description" androID:notificationTimeout="100" androID:packagenames="com.tencent.mm" />
二、主要关注点以及如何在红包到来的时候自动进入页面并自动点击红包
在onAccessibilityEvent方法中监听状态栏的变化,主要有:
AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED、
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED、
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
在响应窗体以及窗体内容变化时处理相关逻辑,获取带微信消息时以下代码打开消息:
//将微信的通知栏消息打开 Notification notification = (Notification) event.getParcelableData(); PendingIntent pendingIntent = notification.contentIntent; try { pendingIntent.send(); } catch (PendingIntent.CanceledException e) { e.printstacktrace(); }
具体代码网上有很多,一般都是通过:findAccessibilityNodeInfosByText、findAccessibilityNodeInfosByVIEwID查找文本或者资源节点进行点击 *** 作,但新版微信开红包页面进行了处理,没有文本信息,而如果采用:
图中resouces-ID这种形式就可能出现这种情况:
在了解整个核心后,获取事件不外乎就是通过文本与ID判断,那么就可以将文本改为图标方式,将ID改为动态ID(每次显示都是随机生成),这样一来就可以提高外挂的门槛。
如何进行规避呢,目前我想的是既然开红包的页面文本和ID都有可能会变,那我们能不能找个不变的进行判断呢,考虑过后,我觉得最可能不变的地方就是开红包这个按钮的位置,也就是图中的bounds,于是在思考过后有了下面的处理:
for (int i = 0; i < nodeInfo.getChildCount(); i++) { //Log.e("TAG","getVIEwIDResourcename :"+nodeInfo.getChild(i).getVIEwIDResourcename()); Rect outBounds = new Rect(); nodeInfo.getChild(i).getBoundsInScreen(outBounds); int left_dp = px2dip(this,400); int top_dp = px2dip(this,1035); int right_dp = px2dip(this,682); int bottom_dp = px2dip(this,1320); int left_px = dip2px(this,left_dp); int top_px = dip2px(this,top_dp); int right_px = dip2px(this,right_dp); int bottom_px = dip2px(this,bottom_dp); Rect mStandar = new Rect(left_px,top_px,right_px,bottom_px); if(mStandar.contains(outBounds)){ Log.e("TAG","outBounds.left :"+outBounds.left+";outBounds.top :"+outBounds.top+";outBounds.right :"+outBounds.right+";outBounds.bottom :"+outBounds.bottom); nodeInfo.getChild(i).performAction(AccessibilityNodeInfo.ACTION_CliCK); break; } }
这里取的矩形区域要比按钮区域稍大点,然后判断到开红包页面按钮是否在我们预先设置的区域内,如果在,我们直接进行点击开红包 *** 作:AccessibilityNodeInfo.ACTION_CliCK。
其他比如如何防止重复抢等细节问题,也是要处理的问题。
好了,直接放下关键代码,仅供参考:
package com.zkhb.weixinqinghongbao.service;import java.util.Date;import java.util.List;import androID.accessibilityservice.AccessibilityService;import androID.annotation.Suppresslint;import androID.annotation.TargetAPI;import androID.app.KeyguardManager;import androID.app.KeyguardManager.keyguardlock;import androID.app.Notification;import androID.app.@R_502_662@;import androID.app.PendingIntent;import androID.content.Context;import androID.content.Intent;import androID.graphics.Rect;import androID.os.Build;import androID.os.Handler;import androID.os.PowerManager;import androID.os.PowerManager.WakeLock;import androID.util.Log;import androID.vIEw.accessibility.AccessibilityEvent;import androID.vIEw.accessibility.AccessibilityManager;import androID.vIEw.accessibility.AccessibilityNodeInfo;import androID.Widget.Toast;import com.zkhb.weixinqinghongbao.MainActivity;import com.zkhb.weixinqinghongbao.R;import com.zkhb.weixinqinghongbao.entity.HongBaoInfo;import com.zkhb.weixinqinghongbao.util.DateFormatUtils;import com.zkhb.weixinqinghongbao.util.LogUtil;/** * * 抢红包服务 */@Suppresslint("NewAPI") public class QiangHongBaoService extends AccessibilityService {// static final String TAG = "QiangHongBao"; /** 微信的包名*/ static final String WECHAT_PACKAGEname = "com.tencent.mm"; /** 红包消息的关键字*/ static final String HONGBAO_TEXT_KEY = "[微信红包]"; /** 红包消息的关键字*/ static final String HONGBAO_TEXT_KEY1 = "微信红包"; private static final int ENVELOPE_RETURN = 0; private static final String LOCK_TAG = "屏幕"; Handler handler = new Handler(); /** 是否在抢红包界面里*/// public boolean isInMM=false; /** 是否可以点击*/// public boolean ISCliCKED=false; /** 是否进入过拆红包界面*/ public static boolean ISCOMINQIANGCHB=false; //真正的 public static boolean ISCOMINQIANGCHB2=false; //真正的判断 public static boolean ISCOMINQIANGCHB3=false; /** 是否来自通知栏*/ private static boolean ISCOMNOTIFY=false; private PowerManager pm; //点亮屏幕 private WakeLock mWakeLock; //解锁锁定屏幕 private keyguardlock keyguardlock; /**判断之前用户是否锁屏 */ private static boolean islock=false; /**通知服务 */ private @R_502_662@ n_manager; public voID unlock(){ if(pm==null){ pm = (PowerManager) getApplication().getSystemService(Context.POWER_SERVICE); } boolean isScreenOn = pm.isScreenOn();//如果为true,则表示屏幕“亮”了,否则屏幕“暗”了。 if(!isScreenOn){ islock=true; KeyguardManager keyguardManager = (KeyguardManager)getSystemService(KEyguard_SERVICE); keyguardlock = keyguardManager.newkeyguardlock(LOCK_TAG); keyguardlock.disableKeyguard(); mWakeLock = pm.newWakeLock(PowerManager.FulL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,LOCK_TAG); mWakeLock.acquire(); } } public voID lock(){ if(islock){ //释放屏幕常亮锁 if(null != mWakeLock) { mWakeLock.release(); } //屏幕锁定 if(keyguardlock!=null){ keyguardlock.reenableKeyguard(); } } } @OverrIDe public voID onAccessibilityEvent(AccessibilityEvent event) { final int eventType = event.getEventType(); LogUtil.info("事件---->" + event); //通知栏事件 if(eventType == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) { unlock(); List<CharSequence> texts = event.getText(); if(!texts.isEmpty()) { for(CharSequence t : texts) { String text = String.valueOf(t); if(text.contains(HONGBAO_TEXT_KEY)) { ISCOMNOTIFY=true; ISCOMINQIANGCHB=false; openNotify(event); break; } } } } else if(eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { unlock(); openHongBao(event);// AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();// List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText = nodeInfo.findAccessibilityNodeInfosByText("领取红包");// if(findAccessibilityNodeInfosByText.isEmpty()){// isInMM=false;// }else{// isInMM=true;// }// List<CharSequence> text = event.getText();// if(text.size()>=0){// CharSequence charSequence = text.get(0);//// if(charSequence.equals("微信")){//// isInMM=true;//// }else{//// isInMM=false;//// }// } }else if(eventType==AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && ISCOMNOTIFY){ unlock(); openHongBao(event); List<AccessibilityNodeInfo> InfoText = getRootInActiveWindow().findAccessibilityNodeInfosByText("领取红包"); if(!InfoText.isEmpty()){ checkKey2(); ISCOMNOTIFY=false; } } } /*@OverrIDe protected boolean onKeyEvent(KeyEvent event) { //return super.onKeyEvent(event); return true; }*/ @OverrIDe public boolean onUnbind(Intent intent) { Toast.makeText(this,"断开抢红包服务",Toast.LENGTH_SHORT).show(); ISCOMINQIANGCHB=false; islock=false; ISCOMINQIANGCHB2=false; ISCOMINQIANGCHB3=false; ISCOMNOTIFY=false; setNotification("已关闭抢红包小助手服务~~",Notification.FLAG_auto_CANCEL,"已关闭抢红包小助手服务~~~"); return super.onUnbind(intent); } @OverrIDe public voID onInterrupt() { Toast.makeText(this,"中断抢红包服务",Toast.LENGTH_SHORT).show(); } @OverrIDe protected voID onServiceConnected() { super.onServiceConnected(); ISCOMINQIANGCHB=false; ISCOMINQIANGCHB2=false; ISCOMINQIANGCHB3=false; islock=false; ISCOMNOTIFY=false; setNotification("已开启抢红包小助手服务~~",Notification.FLAG_NO_CLEAR,"已开启抢红包小助手服务~~~"); Toast.makeText(this,"连接抢红包服务",Toast.LENGTH_SHORT).show(); } private voID setNotification(String content,int flags,String Title) { if(n_manager==null){ n_manager = (@R_502_662@) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); } n_manager.cancelAll(); Notification notification=new Notification(R.drawable.ic_launcher,content,System.currentTimeMillis());// notification.defaults |= Notification.DEFAulT_VIBRATE;// long[] vibrate = {0,100,200,300}; //0毫秒后开始振动,振动100毫秒后停止,再过200毫秒后再次振动300毫秒// notification.vibrate=vibrate; notification.flags |= flags; //表明在点击了通知栏中的"清除通知"后,此通知不清除, Intent notificationIntent = new Intent(this,MainActivity.class); //点击该通知后要跳转的Activity PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),notificationIntent,0); notification.setLatestEventInfo(getApplicationContext(),Title,"进入微信抢红包~~",contentIntent); n_manager.notify(0,notification); } private voID sendNotifyEvent(){ AccessibilityManager manager= (AccessibilityManager)getSystemService(ACCESSIBIliTY_SERVICE); if (!manager.isEnabled()) { return; } AccessibilityEvent event=AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED); event.setPackagename(WECHAT_PACKAGEname); event.setClassname(Notification.class.getname()); CharSequence tickerText = HONGBAO_TEXT_KEY; event.getText().add(tickerText); manager.sendAccessibilityEvent(event); } /** 打开通知栏消息*/ @TargetAPI(Build.VERSION_CODES.JELLY_BEAN) private voID openNotify(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(); } } @TargetAPI(Build.VERSION_CODES.JELLY_BEAN) private voID openHongBao(AccessibilityEvent event) { if("com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyReceiveUI".equals(event.getClassname())) { //点中了红包,下一步就是去拆红包 ISCOMINQIANGCHB=true; ISCOMINQIANGCHB2=true; checkKey1(); } else if("com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI".equals(event.getClassname())) { //拆完红包后看详细的纪录界面 LogUtil.info("事件---->com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI"); //nonething// if(ISCOMINQIANGCHB){// ISCOMINQIANGCHB=false;// } if(ISCOMINQIANGCHB2){ ISCOMINQIANGCHB3=true; }else{ ISCOMINQIANGCHB3=false; } checkKey3(); ISCOMINQIANGCHB=true; ISCOMINQIANGCHB2=false; performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK); if(getSharedPreferences("config",Context.MODE_PRIVATE).getBoolean("auto",false)){ performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME); } lock(); } else if("com.tencent.mm.ui.LauncherUI".equals(event.getClassname())) {// isInMM=true; //在聊天界面,去点中红包 LogUtil.info("事件---->com.tencent.mm.ui.LauncherUI"); checkKey2(); } } @Suppresslint("NewAPI") @TargetAPI(Build.VERSION_CODES.JELLY_BEAN) private voID checkKey3() { AccessibilityNodeInfo nodeInfo = getRootInActiveWindow(); if(nodeInfo == null) { LogUtil.info("rootwindow为空333"); return; } //Todo List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText = nodeInfo.findAccessibilityNodeInfosByText("元"); if(findAccessibilityNodeInfosByText.size()>=0){ AccessibilityNodeInfo accessibilityNodeInfo2 = findAccessibilityNodeInfosByText.get(0).getParent(); CharSequence money = accessibilityNodeInfo2.getChild(2).getText(); CharSequence name = accessibilityNodeInfo2.getChild(0).getText(); if(ISCOMINQIANGCHB3){ HongBaoInfo info=new HongBaoInfo(); info.setStrDateTime(DateFormatUtils.format("yyyy-MM-dd HH:mm:ss",new Date())); info.setStrMoney(money+""); info.setStrname(name+""); info.save(); } Toast.makeText(getApplicationContext(),money+":::"+name,0).show(); }// List<AccessibilityNodeInfo> findAccessibilityNodeInfosByVIEwID = nodeInfo.findAccessibilityNodeInfosByVIEwID("com.tencent.mm:ID/aw8");// AccessibilityNodeInfo accessibilityNodeInfo = findAccessibilityNodeInfosByVIEwID.get(0);// CharSequence text = accessibilityNodeInfo.getText(); } private voID checkKey1() { AccessibilityNodeInfo nodeInfo = getRootInActiveWindow(); if(nodeInfo == null) { LogUtil.info("rootwindow为空11111"); return; } for (int i = 0; i < nodeInfo.getChildCount(); i++) { Log.e("TAG","outBounds.left :"+outBounds.left+";outBounds.top :"+outBounds.top+";outBounds.right :"+outBounds.right+";outBounds.bottom :"+outBounds.bottom); nodeInfo.getChild(i).performAction(AccessibilityNodeInfo.ACTION_CliCK); break; }// nodeInfo.performAction(action)//[405,1042][675,1312] } //List<AccessibilityNodeInfo> List = nodeInfo.findAccessibilityNodeInfosByText("拆红包");// List<AccessibilityNodeInfo> List = nodeInfo.findAccessibilityNodeInfosByVIEwID("com.tencent.mm:ID/b5d");// for(AccessibilityNodeInfo n : List) {// n.performAction(AccessibilityNodeInfo.ACTION_CliCK);// } } private voID checkKey2() { AccessibilityNodeInfo nodeInfo = getRootInActiveWindow(); if(nodeInfo == null) { LogUtil.info("rootwindow为空222222"); return; } List<AccessibilityNodeInfo> List = nodeInfo.findAccessibilityNodeInfosByText("领取红包"); if(List.isEmpty()) { List = nodeInfo.findAccessibilityNodeInfosByText(HONGBAO_TEXT_KEY); for(AccessibilityNodeInfo n : List) { LogUtil.info("-->微信红包:" + n); n.performAction(AccessibilityNodeInfo.ACTION_CliCK); break; } } else { //最新的红包领起 AccessibilityNodeInfo parent = List.get(List.size() - 1).getParent();// Log.w(TAG,"ISCliCKED::"+ISCliCKED)!ISCliCKED; if(parent != null && !ISCOMINQIANGCHB) { parent.performAction(AccessibilityNodeInfo.ACTION_CliCK); }// for(int i = List.size() - 1; i >= 0; i --) {// AccessibilityNodeInfo parent = List.get(i).getParent();// Log.i(TAG,"-->领取红包:" + parent);// if(parent != null && parent.isClickable()) {// parent.performAction(AccessibilityNodeInfo.ACTION_CliCK);// break;// }// }// performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK); } } /** * @param info 当前节点 * @param matchFlag 需要匹配的文字 * @param type *** 作的类型 */ @Suppresslint("NewAPI") public voID recycle(AccessibilityNodeInfo info,String matchFlag,int type) { if (info != null) { if (info.getChildCount() == 0) { CharSequence desrc = info.getContentDescription(); switch (type) { case ENVELOPE_RETURN://返回 if (desrc != null && matchFlag.equals(info.getContentDescription().toString().trim())) { if (info.isCheckable()) { info.performAction(AccessibilityNodeInfo.ACTION_CliCK); } else { performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK); } } break; } } else { int size = info.getChildCount(); for (int i = 0; i < size; i++) { AccessibilityNodeInfo childInfo = info.getChild(i); if (childInfo != null) { LogUtil.info("index: " + i + " info" + childInfo.getClassname() + " : " + childInfo.getContentDescription()+" : "+info.getText()); recycle(childInfo,matchFlag,type); } } } } } @OverrIDe public voID onDestroy() { super.onDestroy(); lock(); } /** * 根据手机的分辨率从 dip 的单位 转成为 px(像素) */ public static int dip2px(Context context,float dpValue) { final float scale = context.getResources().getdisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ public static int px2dip(Context context,float pxValue) { // final float scale = context.getResources().getdisplayMetrics().density; return (int) (pxValue / 3 + 0.5f); //3是本人手机的设备密度 } }
AccessibilityService还可以用在智能安装、虚拟按键上都有很多应用,这样的实践只是给我们一种解决问题另外的一种思路,问题嘛,总还是要解决的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的Android抢红包插件实现原理浅析全部内容,希望文章能够帮你解决Android抢红包插件实现原理浅析所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)