Android 輔助權限與懸浮窗

第一節

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

1、介紹

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

2、配置

一、新建Service並繼承AccessibilityServicewindows

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

二、並配置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>
複製代碼

三、在res目錄下新建xml文件夾,並新建配置文件accessibility.xmlbash

<?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" />
複製代碼

3、核心方法

一、根據界面text找到對應的組件(注:方法返回的是集合,找到的組件不一點惟一,同時這裏的text不僅僅是咱們理解的 TextView 的 Text,還包括一些組件的 ContentDescription)微信

accessibilityNodeInfo.findAccessibilityNodeInfosByText(text)
複製代碼

二、根據組件 id 找到對應的組件(注:方法返回的是集合,找到的組件不一點惟一,組件的 id 獲取能夠經過 Android Studio 內置的工具 monitor 獲取,該工具路徑:C:\Users\Dell\AppData\Local\Android\Sdk\tools)app

accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id)
複製代碼

image

4、輔助權限判斷是否開啓

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;
    }
複製代碼

5、輔助的開啓方法

1.root 受權環境下,無需引導用戶到系統設置頁面開啓ide

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);
                }
            }
        }
    }
複製代碼

第二節

在執行自動化服務的流程中,咱們其實並不但願被用戶的操做中斷流程,因此有什麼方法在用戶點擊自動化操做的過程當中,避免用戶再次操做呢?那就是開啓一個全局透明的懸浮窗,進行屏蔽觸摸事件。

1、懸浮窗

其實一開始,我是想固然的跟之前同樣,開啓一個全屏的透明的懸浮窗,進行遮罩的做用,可是發現,設置 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類型呢,這裏面涉及到懸浮窗的開啓問題了,可自行百度懸浮窗的開啓相關文章。

2、懸浮窗的 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"));
                }
            }
        }
    };
複製代碼

3、懸浮窗開啓引導

爲了更好的用戶體驗,咱們須要給咱們每一步操做一個明確的提示,讓用戶知道須要作些什麼,特別是引導開啓系統權限的時候。

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

一、taskAffinity

簡單講一下這個屬性的意思:默認狀況下,咱們啓動的 Activity 都是歸屬於同包名的任務棧裏面,但若是配置這個屬性,則該 Activity 會在新的任務棧裏面(棧名是你配置的)

android:taskAffinity=".guide"
複製代碼

能夠經過如下命令去查看當前任務棧的信息:

adb shell dumpsys activity activities
複製代碼

二、excludeFromRecents

當配置這個屬性,可讓你的 Activity 不會出如今最近任務列表裏面

android:excludeFromRecents="true"
複製代碼

三、配置 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);
    }
}
複製代碼

四、界面呈現的效果

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

PermissionActivity

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

GuideActivity

4、懸浮窗的實現

在懸浮窗的UI設計上,咱們須要將其設置爲透明背景,這樣對用戶是無感的,整個自動化流程中,實際上是至關於屏幕有個用戶看不到的「保護罩」在確保着你的自動化業務不被「打擾」。在佈局上,咱們須要實現最外層的根佈局的點擊事件,這樣在用戶點擊屏幕的時候,彈窗 Toast 友好提示用戶:自動化業務正在執行,請中止業務才能操做。

image

同時懸浮窗提供「中止」按鈕,能夠終止業務並關閉全屏透明懸浮窗。

5、使用場景

部分軟件須要開啓許多權限才能保證軟件的正常使用,例如市面上的某鎖屏軟件,他們須要涉及至關多的權限,若是一個個讓用戶去開啓,可能找不到對應的權限怎麼開啓,因而他們把這個流程簡化成腳本,只要用戶開啓輔助權限,則跳轉到權限開啓流程,自動到權限頁面,把例如:開機自啓動權限,讀取通知,獲取位置等權限開啓。固然這個過程是被一個界面遮蓋了的,用戶是看不到執行了什麼操做的(這也暴露android的安全性問題)。

image

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

碼農茅草屋
相關文章
相關標籤/搜索