Android Accessibilityservice to implement micro-letter grab Red Envelopes plugin _android

Source: Internet
Author: User
Tags gettext

In your mobile phone more settings or advanced settings, we will find that there is a barrier-free function, many people do not know what the specific function is, in fact, this function is to enhance the user interface to help people with disabilities, or may be temporarily unable to fully interact with the device

Its implementation is run in the background through the Accessibilityservice service, receiving a callback for the specified event through accessibilityevent. Such events indicate some state transitions in the user's interface, such as focus changes, a button being clicked, and so on. Such a service can choose the ability to request the contents of the active window. Simply put, Accessibilityservice is a background monitoring service that invokes the callback method of the backend service when the content you are monitoring changes

Accessibilityservice use

1.1 Creating a service class

Write your own service class, rewrite the Onserviceconnected () method, the Onaccessibilityevent () method, and the Oninterrupt () method

The public class Qhbaccessibilityservice extends Accessibilityservice {

 /**
 * will be invoked when the service is started * *
 @Override
 protected void onserviceconnected () {
 super.onserviceconnected ();
 }

 /**
 * Callback to monitor window changes
 /@Override public
 void Onaccessibilityevent (Accessibilityevent event) {
 int eventtype = Event.geteventtype ();
 Processing based on event callback type
 }

 /**
 * The callback of the
 service
 /@Override public
 void Oninterrupt () {

 }
}

The following is an introduction to the methods commonly used in Accessibilityservice

Disableself (): Disables the current service, which means that the service can stop running by this method
Findfoucs (int falg): Find a control that has a specific focus type
Getrootinactivewindow (): If the configuration can get the contents of the window, it returns the root node of the currently active window
Getseviceinfo (): Get configuration information for current service
Onaccessibilityevent (Accessibilityevent Event): callback function for Accessibilityevent event, System passed Sendaccessibiliyevent () Constantly send accessibilityevent to here
performglobalaction (int action): Perform global operations, such as return, back to the home page, open the most recent actions
Setserviceinfo (accessibilityserviceinfo info): Set configuration information for the current service
Getsystemservice (String name): Getting system services
Onkeyevent (KeyEvent Event): If the service is allowed to listen for keystrokes, this method is a callback to the keystroke event, which requires attention, which occurs before the system processes the key event
Onserviceconnected (): The system is triggered when the service is successfully bound, that is, when you open the appropriate service in the setup, the system will trigger when it successfully binds the service, usually we can do some initialization here
Oninterrupt (): Callback when service is interrupted

1.2 Declaration Service

Since it's a background service, we need to configure the service information in manifests

<service
 android:name= ". Accessibilityservice.qhbaccessibilityservice "
 android:enabled=" true "
 android:exported=" true
 " Android:label= "@string/label"
 android:permission= "Android.permission.BIND_ACCESSIBILITY_SERVICE" >
 <intent-filter>
 <action android:name= "Android.accessibilityservice.AccessibilityService"/>
 </intent-filter>
</service>

We must note that any one information configuration error will cause the service to be unresponsive

Android:label: Displays the name of the service in the accessibility list

Android:permission: You need to specify Bind_accessibility_service permissions, which are more than 4.0 of the system requirements
Intent-filter: This name is fixed.

1.3 Configuring Service Parameters

Configuration service parameters are: configured to accept events of a specified type, listen for specified package, retrieve window contents, get event Type time, and so on. There are two ways to configure the service parameters:

Method One: After Android 4.0, you can specify an XML file to configure by using the Meta-data tag
Method Two: Configure parameters dynamically through code

1.3.1 Method A

Add the Meta-data tag to the original manifests to specify the XML file

<service
 android:name= ". Accessibilityservice.qhbaccessibilityservice "
 android:enabled=" true "
 android:exported=" true
 " Android:label= "@string/label"
 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/accessibility_service_config"/>
</service>

Next is the configuration of the Accessibility_service_config file

<?xml version= "1.0" encoding= "Utf-8"?> <accessibility-service xmlns:android=
"http://" Schemas.android.com/apk/res/android "
 android:accessibilityeventtypes=" typenotificationstatechanged| Typewindowstatechanged|typewindowcontentchanged|typewindowschanged "
 android:accessibilityfeedbacktype=" Feedbackgeneric "
 android:accessibilityflags=" Flagdefault "
 android:canretrievewindowcontent=" true "
 android:description= "@string/description"
 android:notificationtimeout= "android:packagenames="
 Com.tencent.mm "/>

The following is an introduction to XML parameters

Accessibilityeventtypes: Indicates what the service is interested in the changes in the interface, that is, which event notifications, such as window opening, sliding, focus change, long press, and so on. Specific values can be found in the Accessibilityevent class, such as Typeallmask to accept all event notifications
Accessibilityfeedbacktype: Feedback means, such as voice playback, or vibration
Canretrievewindowcontent: Indicates whether the service can access content in the active window. That is, if you want to get the form content in the service, you need to set its value to True
Description: The description of the barrier-free function, embodied in the following figure

Notificationtimeout: The interval at which events are accepted, usually set to 100
Packagenames: Indicates the event that the service is used to monitor which package is generated, and here take the packet name of the micro-letter as an example

1.3.2 Method II

Configure Accessibilityserviceinfo information for our Accessibilityservice by code, where we can extract a method to set

private void Settingaccessibilityinfo () {
 string[] packagenames = {"com.tencent.mm"};
 Accessibilityserviceinfo maccessibilityserviceinfo = new Accessibilityserviceinfo ();
 The type of response event, where all response events (long press, click, Slide, etc.)
 maccessibilityserviceinfo.eventtypes = Accessibilityevent.types_all_mask;
 Feedback to the user type, here is the voice cue
 maccessibilityserviceinfo.feedbacktype = Accessibilityserviceinfo.feedback_spoken;
 The filtered package name
 maccessibilityserviceinfo.packagenames = packagenames;
 Setserviceinfo (Maccessibilityserviceinfo);
}

The Accessibilityserviceinfo class is involved here, and the Accessibilityserviceinfo class is used to configure Accessibilityservice information, This class contains a large number of constant fields for configuration and XML attributes, which are common: Accessibilityeventtypes,canrequestfilterkeyevents,packagenames and so on.

1.4 Start Service

Here we need to manually open the feature in the accessibility function, otherwise we can not continue, through the following code to open the System accessibility list

Intent Intent = new Intent (settings.action_accessibility_settings);
StartActivity (Intent);

1.5 Handling Event Information

As we monitor the event notification bar and interface information, when we specify Packagenames notification bar or interface changes, will be through Onaccessibilityevent callback our events, and then the event processing

@Override public
void Onaccessibilityevent (Accessibilityevent event) {
 int eventtype = Event.geteventtype (); c10/>//process switch (eventtype) depending on the event callback type
 {
 //when the notification bar changes, case
 Accessibilityevent.type_notification_ State_changed: Break

  ;
 Case Accessibilityevent.type_window_state_changed when the state of the window changes
 : Break

  ;
 }


When we receive the notification, the status bar will have a push message to arrive, this time will be type_notification_state_changed listening, the implementation of the content, when we switch the micro-interface, or use the micro-letter, this time will be type_ Window_state_changed Monitor, execute the contents inside

The method of Accessibilityevent

Geteventtype (): Event type
GetSource (): Gets the node information for the event source
GetClassName (): Gets the type of the event source's corresponding class, such as when a click event is generated by a button, then the full class name of the button is obtained.
GetText (): Gets the text information of the event source, such as the event is issued by TextView, at this time gets is the TextView Text property. If the event source is a tree structure, then the collection of all values with the Text property on the tree is obtained at this time
IsEnabled (): Whether the event source (the corresponding interface control) is in the available state
GetItemCount (): If the event source is a tree structure, the number of nodes in the root node will be returned

1.6 Getting node information

When the interface window changes, the node of the control is fetched. The node nature of the entire window is a tree structure, through the following operation node information

1.6.1 Get window node (root node)

Accessibilitynodeinfo nodeinfo = Getrootinactivewindow ();

1.6.2 Gets the specified child node (control node)

Find the corresponding node set through the text
list<accessibilitynodeinfo> List = nodeinfo.findaccessibilitynodeinfosbytext (text);
Find the corresponding set of nodes through the control ID, such as com.tencent.mm:id/gd
list<accessibilitynodeinfo> List = Nodeinfo.findaccessibilitynodeinfosbyviewid (Clickid);

1.7 Analog Node Click

When we get the node information, the control node for analog click, long press and other operations, Accessibilitynodeinfo class provides a performaction () method to perform the simulation operation, the specific operation can be seen in the official document introduction, here Enumerate common operations

Analog Click
accessibilitynodeinfo.performaction (accessibilitynodeinfo.action_click);
Analog Long Press
accessibilitynodeinfo.performaction (Accessibilitynodeinfo.action_long_click);
The simulation obtains the focus
accessibilitynodeinfo.performaction (accessibilitynodeinfo.action_focus);
Simulate paste
accessibilitynodeinfo.performaction (accessibilitynodeinfo.action_paste);

Grab the red envelope plug-in implementation

2.1 Principle Analysis

1, received micro-letter red packets push information, in the push information to determine whether there is "[micro-letter Red envelopes]" message prompts, if there is a click into the chat interface
2, by traversing the window tree node, found with "Collect red envelopes" the words of the node, then click Enter, that is, red envelopes, pop-up grab red envelopes interface
3, in the grab the Red envelope interface, through the ID get "open" button node, then open red envelopes
4, in the Red Envelope details page, through the ID get back the Key button node, click and return to the micro-mail chat interface

2.2 Points to note

1, because the micro-letter each version of the button ID is not the same, in our program is necessary to modify the button ID to achieve the version of the Fit
2, in obtaining the control ID, pay attention to its layout is clickable, otherwise get the control can not be clicked, will make the program unresponsive

2.3 Getting the control ID

When our phone is connected to a USB cable, select the device in the Android Device Monitor and open the dump View hierarchy for UI Automator tool, which allows you to get control information

Get the Open button ID and return button ID

2.4 Code implementation

Note: This is a version of the control ID of the micro-letter latest 6.3.30, and if it is a different version, please fit it yourself

/** * ===== Author ===== * Xu Handsome * ===== Time ===== * 2016/11/19. * * public class Qhbaccessibilityservice extends Accessibilityservice {private list<accessibilitynodeinfo> Parent

 S
  /** * When starting the service will be called * * @Override protected void onserviceconnected () {super.onserviceconnected ();
 Parents = new arraylist<> (); /** * Callback for monitoring window changes/@Override public void Onaccessibilityevent (Accessibilityevent event) {int eventtype = even
  T.geteventtype (); Switch (EventType) {//Case ACCESSIBILITYEVENT.TYPE_NOTIFICATION_STATE_CHANGED:LIST&LT;CHARSEQUENCE&G when notification bar changes T
    texts = Event.gettext ();
      if (!texts.isempty ()) {for (charsequence text:texts) {String content = text.tostring ();
         if (Content.contains ("[micro-red envelope]") {//analog opens the notification bar message, that is, open the micro-letter if (Event.getparcelabledata ()!= null && Event.getparcelabledata () instanceof Notification) {Notification Notification = (Notification) Event.getparcela
        Bledata (); PEndingintent pendingintent = notification.contentintent;
         try {pendingintent.send ();
        LOG.E ("Demo", "Enter micro-letter");
        catch (Exception e) {e.printstacktrace ();
   The break is in}}}}; Case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:String ClassName = Event.getclassname () when the State of the window changes. ToString ()
    ;
     if (Classname.equals ("Com.tencent.mm.ui.LauncherUI")) {//Click on the last Red Envelope log.e ("Demo", "click Red Envelope");
    Getlastpacket (); else if (classname.equals ("Com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyReceiveUI")) {//Open red Envelope log.e ("demo", "Open red
     Package ");
    Inputclick ("Com.tencent.mm:id/bg7"); else if (classname.equals ("Com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI")) {//exit Red Envelope LOG.E ("demo", "Exit
     Red envelopes ");
    Inputclick ("com.tencent.mm:id/gd");
  } break; /** * Gets the control via ID and simulates clicking * @param clickid/@TargetApi (build.version_codes. JELLY_BEAN_MR2) private void Inputclick (String cLickid) {Accessibilitynodeinfo nodeinfo = Getrootinactivewindow (); 
   if (nodeinfo!= null) {list<accessibilitynodeinfo> List = Nodeinfo.findaccessibilitynodeinfosbyviewid (clickId);
   for (Accessibilitynodeinfo item:list) {item.performaction (Accessibilitynodeinfo.action_click); }}/** * Gets the last red envelope in the list and simulates clicking/private void Getlastpacket () {Accessibilitynodeinfo RootNode = Getrootin
  ActiveWindow ();
  Recycle (RootNode);
  if (Parents.size () >0) {Parents.get (Parents.size ()-1). Performaction (Accessibilitynodeinfo.action_click);
  }/** * Regression function traverses each node and will contain "collect red envelopes" into the list * * @param info/public void recycle (Accessibilitynodeinfo info) {
     if (info.getchildcount () = = 0) {if (Info.gettext ()!= null) {if ("Collect red envelopes". Equals (Info.gettext (). toString ())) {
     if (info.isclickable ()) {info.performaction (Accessibilitynodeinfo.action_click);
     } accessibilitynodeinfo Parent = Info.getparent (); while (parent!= null) {
      if (parent.isclickable ()) {Parents.add (parent);
      Break
     Parent = Parent.getparent (); else {for (int i = 0; i < Info.getchildcount (); i++) {if (Info.getchild (i)!= null) {RE
    Cycle (Info.getchild (i));

 \/** * Interrupt Service callback/@Override public void Oninterrupt () {}}}

When you receive a red envelope, log prints the information

11-21 13:53:06.275 2909-2909/com.handsome.boke2 E/demo: Entering the micro-letter
11-21 13:53:06.921 2909-2909/com.handsome.boke2 e/demo: Click on red Envelopes
11-21 13:53:07.883 2909-2909/com.handsome.boke2 e/demo: Open Envelopes
11-21 13:53:08.732 2909-2909/com.handsome.boke2 E/demo: Exit Red Envelopes

You may think of doing some software to steal information, such as access to QQ password, Alipay password and so on, Haha, General edittext set InputType as password type, can not get its input value

2.5 Source Download: Http://xiazai.jb51.net/201611/yuanma/Androidwxpackage (jb51.net). rar

This article has been organized into the "Android micro-credit Development tutorial Summary," Welcome to learn to read.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.