Android抢红包插件实现原理浅析
抢红包,先看效果图~
实现自动抢红包,解决问题有两点:
一:如何实时监听发红包的事件
二:如何在红包到来的时候自动进入页面并自动点击红包
一、如何获取红包到来的事件
为了获取红包到来状态栏的变化,我们要用到一个类: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.notificationmanager; 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 notificationmanager 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 = (notificationmanager) 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(),0,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", "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; } // 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还可以用在智能安装、虚拟按键上都有很多应用,这样的实践只是给我们一种解决问题另外的一种思路,问题嘛,总还是要解决的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。