Android 輔助許可權與懸浮窗

幕後眼光發表於2019-01-21

第一節

本文旨在介紹AccessibilityService如果更優雅的使用,以及使用過程遇到的問題,該怎麼解決。

一、介紹

輔助功能服務在後臺執行,並在觸發AccessibilityEvent時由系統接收回撥。這樣的事件表示使用者介面中的一些狀態轉換,例如,焦點已經改變,按鈕被點選等等。現在常用於自動化業務中,例如:微信自動搶紅包外掛,微商自動加附近好友,自動評論朋友,點贊朋友圈,甚至運用在群控系統,進行刷單

二、配置

1、新建Service並繼承AccessibilityService

    /**
     * 核心服務:執行自動化任務
     * Created by czc on 2017/6/13.
     */
    public class TaskService_ extends AccessibilityService{
        @Override
        public void onAccessibilityEvent(AccessibilityEvent event) {
            //注意這個方法回撥,是在主執行緒,不要在這裡執行耗時操作
        }
        @Override
        public void onInterrupt() {
    
        }
    }
複製程式碼

2、並配置AndroidManifest.xml

    <service
        android:name=".service.TaskService"
        android:enabled="true"
        android:exported="true"
        android:label="@string/app_name_setting"
        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>
複製程式碼

3、在res目錄下新建xml資料夾,並新建配置檔案accessibility.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"
     <!--監視的view的狀態,注意這裡設定flagDefault會到時候部分介面狀態改變,不觸發onAccessibilityEvent(AccessibilityEvent event)的回撥-->
    android:accessibilityFlags="flagDefault|flagRetrieveInteractiveWindows|flagIncludeNotImportantViews|flagReportViewIds|flagRequestTouchExplorationMode"
    <!--是否要能夠檢索活動視窗的內容,此設定不能在執行時改變-->
    android:canRetrieveWindowContent="true"
    <!--功能描述-->
    android:description="@string/description"
    <!--同一事件間隔時間名-->
    android:notificationTimeout="100" 
    <!--監控的軟體包名-->
    android:packageNames="com.tencent.mm,com.eg.android.AlipayGphone" />
複製程式碼

三、核心方法

1、根據介面text找到對應的元件(注:方法返回的是集合,找到的元件不一點唯一,同時這裡的text不單單是我們理解的 TextView 的 Text,還包括一些元件的 ContentDescription)

accessibilityNodeInfo.findAccessibilityNodeInfosByText(text)
複製程式碼

2、根據元件 id 找到對應的元件(注:方法返回的是集合,找到的元件不一點唯一,元件的 id 獲取可以通過 Android Studio 內建的工具 monitor 獲取,該工具路徑:C:\Users\Dell\AppData\Local\Android\Sdk\tools)

accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id)
複製程式碼

image

四、輔助許可權判斷是否開啟

    public static boolean hasServicePermission(Context ct, Class serviceClass) {
        int ok = 0;
        try {
            ok = Settings.Secure.getInt(ct.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
        }

        TextUtils.SimpleStringSplitter ms = new TextUtils.SimpleStringSplitter(':');
        if (ok == 1) {
            String settingValue = Settings.Secure.getString(ct.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                ms.setString(settingValue);
                while (ms.hasNext()) {
                    String accessibilityService = ms.next();
                    if (accessibilityService.contains(serviceClass.getSimpleName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
複製程式碼

五、輔助的開啟方法

1.root 授權環境下,無需引導使用者到系統設定頁面開啟

    public static void openServicePermissonRoot(Context ct, Class service) {
        String cmd1 = "settings put secure enabled_accessibility_services  " + ct.getPackageName() + "/" + service.getName();
        String cmd2 = "settings put secure accessibility_enabled 1";
        String[] cmds = new String[]{cmd1, cmd2};
        ShellUtils.execCmd(cmds, true);
    }
複製程式碼

2.targetSdk 版本小於23的情況下,部分手機也可通過以下程式碼開啟許可權,為了相容,最好 try...catch 以下異常

    public static void openServicePermission(Context ct, Class serviceClass) {
        Set<ComponentName> enabledServices = getEnabledServicesFromSettings(ct, serviceClass);
        if (null == enabledServices) {
            return;
        }
        ComponentName toggledService = ComponentName.unflattenFromString(ct.getPackageName() + "/" + serviceClass.getName());
        final boolean accessibilityEnabled = true;
        enabledServices.add(toggledService);
        // Update the enabled services setting.
        StringBuilder enabledServicesBuilder = new StringBuilder();
        for (ComponentName enabledService : enabledServices) {
            enabledServicesBuilder.append(enabledService.flattenToString());
            enabledServicesBuilder.append(":");
        }
        final int enabledServicesBuilderLength = enabledServicesBuilder.length();
        if (enabledServicesBuilderLength > 0) {
            enabledServicesBuilder.deleteCharAt(enabledServicesBuilderLength - 1);
        }
        Settings.Secure.putString(ct.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, enabledServicesBuilder.toString());
        // Update accessibility enabled.
        Settings.Secure.putInt(ct.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, accessibilityEnabled ? 1 : 0);
    }

    public static Set<ComponentName> getEnabledServicesFromSettings(Context context, Class serviceClass) {
        String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        if (enabledServicesSetting == null) {
            enabledServicesSetting = "";
        }
        Set<ComponentName> enabledServices = new HashSet<ComponentName>();
        TextUtils.SimpleStringSplitter colonSplitter = new TextUtils.SimpleStringSplitter(':');
        colonSplitter.setString(enabledServicesSetting);
        while (colonSplitter.hasNext()) {
            String componentNameString = colonSplitter.next();
            ComponentName enabledService = ComponentName.unflattenFromString(componentNameString);
            if (enabledService != null) {
                if (enabledService.flattenToString().contains(serviceClass.getSimpleName())) {
                    return null;
                }
                enabledServices.add(enabledService);
            }
        }
        return enabledServices;
    }
複製程式碼

3.引導使用者到系統設定介面開啟許可權

    public static void jumpSystemSetting(Context ct) {
        // jump to setting permission
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ct.startActivity(intent);
    }
複製程式碼

4.結合一起,我們可以這樣開啟輔助許可權

    public static void openServicePermissonCompat(final Context ct, final Class service) {
        //輔助許可權:如果root,先申請root許可權
        if (isAppRoot()) {
            if (!hasServicePermission(ct, service)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        openServicePermissonRoot(ct, service);
                    }
                }).start();
            }
        } else {
            try {
                openServicePermission(ct, service);
            } catch (Exception e) {
                e.printStackTrace();
                if (!hasServicePermission(ct, service)) {
                    jumpSystemSetting(ct);
                }
            }
        }
    }
複製程式碼

第二節

在執行自動化服務的流程中,我們其實並不希望被使用者的操作中斷流程,所以有什麼方法在使用者點選自動化操作的過程中,避免使用者再次操作呢?那就是開啟一個全域性透明的懸浮窗,進行遮蔽觸控事件。

一、懸浮窗

其實一開始,我是想當然的跟以前一樣,開啟一個全屏的透明的懸浮窗,進行遮罩的作用,但是發現,設定 Type 為 TYPE_TOAST 或者 TYPE_SYSTEM_ALERT 這樣的懸浮窗某些型別的不同,會導致不單單把使用者的操作遮蔽了,甚至視窗的一些狀態改變也遮蔽的,導致輔助許可權的 onAccessibilityEvent() 方法不回撥,於是去找官方文件,查詢相關懸浮窗的 Type 型別設定。然後被我找到這個屬性值的 Type :

LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
複製程式碼

我們再來看官方解釋:

Windows that are overlaid only by a connected AccessibilityService for interception of user interactions without changing the windows an accessibility service can introspect. In particular, an accessibility service can introspect only windows that a sighted user can interact with which is they can touch these windows or can type into these windows. For example, if there is a full screen accessibility overlay that is touchable, the windows below it will be introspectable by an accessibility service even though they are covered by a touchable window.

雖然官方寫的一大堆,但是我們大概能 get 到裡面的意思,其實就是設定為這個型別的懸浮窗,能夠使輔助功能繼續響應相關視窗與內容的變化。經測試,果然設定這個型別的懸浮窗,可以一方面遮蔽使用者的觸控事件,另一方繼續響應自動點選的相關操作。

    public void createFullScreenView(Context context) {
        WindowManager windowManager = getWindowManager(context);
        if (fullScreenView == null) {
            fullScreenView = new FloatWindowFullScreenView(context);
            LayoutParams fullScreenParams = new LayoutParams();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                fullScreenParams.type = LayoutParams.TYPE_ACCESSIBILITY_OVERLAY;
            } else {
                fullScreenParams.type = LayoutParams.TYPE_TOAST;
            }
            fullScreenParams.format = PixelFormat.TRANSLUCENT;
            fullScreenParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
            fullScreenParams.gravity = Gravity.CENTER;
            windowManager.addView(fullScreenView, fullScreenParams);
        }
    }
複製程式碼

值得注意的是,這個屬性是在 android 5.1 之後加入進來,對於之前的版本,經測試,使用 Toast 型別,也能執行相關操作,至於為什麼 5.1 之後不繼續使用Toast型別呢,這裡面涉及到懸浮窗的開啟問題了,可自行百度懸浮窗的開啟相關文章。

二、懸浮窗的 Context

我們一般開啟懸浮窗的過程中,Context 的傳遞我們使用的 Service 或者 Activity,不過如果設定為 TYPE_ACCESSIBILITY_OVERLAY 的懸浮窗,是隻能傳入你繼承自 AccessibilityService 的服務(Context,否則會報 Is Activity Running 這個異常,那如何在這個服務裡面開啟懸浮窗呢?我是使用廣播的形式去開啟的:

    // 註冊廣播接聽者
    IntentFilter filter = new IntentFilter();
    filter.addAction(Const.ACTION_SHOW_COVER_VIEW);
    filter.addAction(Const.ACTION_SHOW_SMALL_VIEW);
    filter.addAction(Const.ACTION_SET_COVER_VIEW_TIPS);
    registerReceiver(mReceiver, filter);
        
    ....省略其他程式碼
    
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Const.ACTION_SHOW_COVER_VIEW)) {
                if (!FloatWindowManager.getInstance().isFullWindowShowing()) {
                    FloatWindowManager.getInstance().createFullScreenView(TaskService.this);
                }
                String toast = intent.getStringExtra(Const.EXTRA_WINDOW_TOAST);
                if (!StringUtils.isEmpty(toast)) {
                    FloatWindowManager.getInstance().showToast(toast);
                }
            } else if (action.equals(Const.ACTION_SHOW_SMALL_VIEW)) {
                if (!FloatWindowManager.getInstance().isSmallWindowShowing()) {
                    FloatWindowManager.getInstance().createSmallWindow(TaskService.this);
                }
            }else if (action.equals(Const.ACTION_SET_COVER_VIEW_TIPS)) {
                if (FloatWindowManager.getInstance().isFullWindowShowing()) {
                    FloatWindowManager.getInstance().showTipst(intent.getStringExtra("tips"));
                }
            }
        }
    };
複製程式碼

三、懸浮窗開啟引導

為了更好的使用者體驗,我們需要給我們每一步操作一個明確的提示,讓使用者知道需要做些什麼,特別是引導開啟系統許可權的時候。

關於懸浮窗的開啟,之前有寫過一篇文章,Android 懸浮窗踩坑體驗,裡面有介紹關於懸浮窗的開啟、許可權以及自定義懸浮窗。不過這裡我要介紹的是另一種特殊的技巧,在沒有開啟懸浮窗許可權的情況下,用一個特殊的 Activity 來代替懸浮窗。先介紹兩個 Activity 在 AndroidManifest 屬性:

1、taskAffinity

簡單講一下這個屬性的意思:預設情況下,我們啟動的 Activity 都是歸屬於同包名的任務棧裡面,但如果配置這個屬性,則該 Activity 會在新的任務棧裡面(棧名是你配置的)

android:taskAffinity=".guide"
複製程式碼

可以通過以下命令去檢視當前任務棧的資訊:

adb shell dumpsys activity activities
複製程式碼

2、excludeFromRecents

當配置這個屬性,可以讓你的 Activity 不會出現在最近任務列表裡面

android:excludeFromRecents="true"
複製程式碼

3、配置 Activity 主題是全屏透明

android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
複製程式碼

為什麼要配置這兩個屬性呢? 因為我們不希望這個特殊的Activity出現在最近的使用列表裡面,同時配置 taskAffinity 是為了讓這個 Activity 在新的任務棧裡面,使得它在 finish 的時候,不是回到我們之前啟動過的前一個 Activity (並不想影響我們之前的任務棧),這樣的做法就能夠在其他 App 介面顯示我們的 Activity,需要特別說明的的是:啟動該 Acitivity 需要配合 Intent.FLAG_ACTIVITY_NEW_TASK 標識啟動。程式碼如下:

<activity
    android:name="com.czc.ui.act.GuideActivity"
    android:taskAffinity=".guide"
    android:excludeFromRecents="true"
    android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
</activity>
複製程式碼

完整程式碼:

public class GuideActivity extends Activity {

    public static void start(Activity act, String message) {
        Intent intent = new Intent(act, GuideActivity.class);
        intent.putExtra("message", message);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        act.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);

        //設定Activity介面大小
        Window window = getWindow();
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        WindowManager.LayoutParams params = window.getAttributes();
        params.x = 0;
        params.y = 0;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.height = ScreenUtil.dip2px(80);
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(params);

        TextView tvMessage = findViewById(R.id.tv_message);
        tvMessage.setText(getIntent().getStringExtra("message"));

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
            // 5s 後自動關閉提示
                finish();
            }
        }, 5000);
    }
}
複製程式碼

4、介面呈現的效果

1.檢測到沒有【懸浮窗許可權】或者【輔助許可權】,彈出許可權設定頁面 PermissionActivity

PermissionActivity

2.跳轉系統設定裡面的同時【彈出】 GuideActivity

GuideActivity

四、懸浮窗的實現

在懸浮窗的UI設計上,我們需要將其設定為透明背景,這樣對使用者是無感的,整個自動化流程中,其實是相當於螢幕有個使用者看不到的“保護罩”在確保著你的自動化業務不被“打擾”。在佈局上,我們需要實現最外層的根佈局的點選事件,這樣在使用者點選螢幕的時候,彈窗 Toast 友好提示使用者:自動化業務正在執行,請停止業務才能操作。

image

同時懸浮窗提供“停止”按鈕,可以終止業務並關閉全屏透明懸浮窗。

五、使用場景

部分軟體需要開啟許多許可權才能保證軟體的正常使用,例如市面上的某鎖屏軟體,他們需要涉及相當多的許可權,如果一個個讓使用者去開啟,可能找不到對應的許可權怎麼開啟,於是他們把這個流程簡化成指令碼,只要使用者開啟輔助許可權,則跳轉到許可權開啟流程,自動到許可權頁面,把例如:開機自啟動許可權,讀取通知,獲取位置等許可權開啟。當然這個過程是被一個介面遮蓋了的,使用者是看不到執行了什麼操作的(這也暴露android的安全性問題)。

image

更多技術分享,請加微信公眾號——碼農茅草屋:

碼農茅草屋

相關文章