Android development based on Accessibilityservice enables chat bots to tune up other applications

Source: Internet
Author: User

Objective

A few days ago saw a very interesting application video "little" interactive robot, one of which is the user to send it a text/voice, such as "I want to order a chicken steak", and then "tiny" automatically pop up the app, and "chicken" search and other operations, such as the simplified demo shown.

At that time, I felt this kind of interactive way is very interesting, on the Android also has a certain program can be achieved, today based on Accessibilityservice to achieve a bit. (The demo eliminates some of the natural language processing applications, and is also learning this knowledge recently).

First, the simplification of the demo

In the demo, the original input frame and the user's natural language processing are omitted, and a button is placed directly to search for the chicken in the American Regiment application.

  1. Simple layout file: The Meituan function in activity is called after the button is clicked

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.cxmscb.cxm.arobot.MainActivity">    <Button        android:onClick="meituan"        android:textSize="16sp"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="我想在美团买鸡排" /></LinearLayout>
  2. The activity that corresponds to the layout:

    public class Mainactivity extends Appcompatactivity {//used to get the intent Messenger Packagemanager Packagemanager to get open American regiment;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Get the installation package Manager Packagemanager = This.getpackagemanager ();        Used to allow the user to open the accessibility of the app so that the auxiliary service will be effective Intent Intent = new Intent (settings.action_accessibility_settings);    StartActivity (Intent); The public void Meituan (view view) {//sets the secondary service as running state.        This is done primarily to not disrupt the user's autonomous operation of the application Myapplication.getinstance (). Setflag (True);        Set the information variable myapplication.getinstance (). SetParams ("chicken Steak"); Get started Intent Intent Intent = packagemanager.getlaunchintentforpackage ("Com.sankuai.meituan");//"Jp.co.johospace        . Jorte "is where we get the package name to launch the app//each time you launch the US app, but open Intent.setflags as a restart app (Intent.flag_activity_clear_task);    Jump StartActivity (Intent); } @Override Protected void Onresume () {super.onresume ();        Set the secondary service to a non-running state.    Myapplication.getinstance (). Setflag (false); }}
Second, the application of Accessibilityservice

In Mainacitivity, we ask the user to open the app's accessibility service, primarily to enable the application's ancillary services to take effect. In order to avoid the use of ancillary services at any time with the engraved operation, we have also set a flag on it.

  1. The XML configuration for the custom accessibilityservice:

    <accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"    android:description="@string/accessibility_service_description"    android:accessibilityEventTypes="typeAllMask"    android:accessibilityFlags="flagDefault"    android:accessibilityFeedbackType="feedbackGeneric"    android:canRetrieveWindowContent="true"    />

    Where description is the description string for the accessibility that the user allows to apply, there is no application packagenames specified to be assisted, and when not specified, all apps are assisted by default. Typeallmask is the type of Set response event, Feedbackgeneric is the way to set the feedback to the user, with voice broadcast and vibration.

  2. Registration of the custom Accessibilityservice in the mainfest manifest file:

       <service        android:name=".MyAccessibilityService"        android: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>

    Where label is the name that the user sees in the list of accessibility features, with the appropriate permissions and action added, and the configuration of Accessibilityservice in Meta-data.

  3. Specific implementations in custom Accessibilityservice

    When the accessibility of the app is started, there is a backend service that will monitor the phone interface for events, and perform some function callbacks, such as the onaccessibilityevent function, where the current window event is passed in. We need to determine the event type and resolve the layout in the window to get the controls in the specified layout.

    For layout controls in the US app, we can use DDMS to get to, for example, the first page layout of the group:

    After opening the app, we'll need to click on the "Search for business ..." control at the top of the search. So we need to specify when the page arrives, parse to the control, and click on the control (or its parent layout). Similar to other pages. (There are also some controls in the page that require input files).

    We can do this "search Merchant ..." Control class is TextView, we can specify "type" and the class to search for the control.

    public class Myaccessibilityservice extends Accessibilityservice {//The current event occurs with the package name String Nowpackagename; @TargetApi (build.version_codes. JELLY_BEAN_MR2) @Override public void Onaccessibilityevent (Accessibilityevent event) {//Gets the package name of the current event no        Wpackagename = Event.getpackagename (). toString (); Determine if the current state is a running state if it is a nowpackagename.equals ("Com.sankuai.meituan") &&myapplication.getinstance () . Getflag ()) {//Determine if the desired window state changes if (Event.geteventtype () ==accessibilityevent.type_window_state_chang                ED) {//Get event active window layout root node accessibilitynodeinfo rootNode = This.getrootinactivewindow ();            Parse root node handle (RootNode); }}} @TargetApi (Build.version_codes. Jelly_bean) Private Boolean handle (Accessibilitynodeinfo info) {//determines if the node has child controls if (Info.getchildcount () = = 0) {//Determine if the node has text and have "search" text if (Info.gettext ()! = Null& &info.gettext (). ToString (). Contains ("search") {//Group's first page layout: Determine if the node is TextView, if the text matches if ("Search                    Merchant, category, or Business circle. Equals (Info.gettext (). toString ()) && "Android.widget.TextView". Equals (Info.getclassname ())) {                    Determines whether the node control is clickable, clicks its parent layout, and so on.                    Accessibilitynodeinfo parent = info;                            while (Parent!=null) {if (parent.isclickable ()) {//Analog click, jump out of loop                            Parent.performaction (Accessibilitynodeinfo.action_click);                        Break                    } parent = Parent.getparent (); }}//To judge the second layout: Determine if it is an Eidttext object else if ("search for a merchant, category, or Business Circle". Equals (Info.gettext (). toString ()) && "Android.widget.EditText". Equals (Info.getclassname ())) {//Enter text in the form of a clipboard C Lipboardmanager Clipboardmanager = (clipboardmanager) getsystemservice (CLIpboard_service);                    Clipdata clipdata =clipdata.newplaintext ("SCB", Myapplication.getinstance (). Getparams ());                    Clipboardmanager.setprimaryclip (Clipdata);                Simulated paste info.performaction (accessibilitynodeinfo.action_paste); The third layout is judged by whether it is a textview else if the word "search". Equals (Info.gettext (). toString ()) && "Android.wi Dget.  TextView ". Equals (Info.getclassname ())) {//control click on the same principle accessibilitynodeinfo parent                    = info; while (Parent!=null) {if (parent.isclickable ()) {parent.performaction (Acc                            Essibilitynodeinfo.action_click);                        Break                    } parent = Parent.getparent ();                    }//After the service is finished, set flag myapplication.getinstance (). Setflag (false); Return TruE                }else {//other conditions Set flag myapplication.getinstance (). Setflag (false); }}}} else {//When the current node has child controls, the child that resolves it, with this recursive for (int i = 0; i < Info.getchildcount ();                i++) {if (Info.getchild (i)!=null) {Handle (Info.getchild (i));    }}} return false;    } @Override public void Oninterrupt () {Toast.maketext (this, "ZZ", Toast.length_short). Show (); }}

    As you can see, the above code is based on the logic of the American Regiment's search process.

Third, thinking
    1. As we can see from the code, calls to other applications are too dependent on their application and depend on their layout, and when the layout of other applications changes, the functionality will not take effect.

    2. From the code we can also see that this call to other applications is very difficult to modularize, it is easy to lead to too much code, when the application of support calls, the code will increase a lot.

    3. There are too many middle page links during the tuning process for US-group applications.

Four, demo codeGithub

Android development based on Accessibilityservice enables chat bots to tune up other applications

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.