Android辅助权限的介绍和配置完整记录

所属分类: 软件编程 / Android 阅读数: 43
收藏 0 赞 0 分享

前言

本文旨在介绍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)

使用 Monitor 工具获取节点 id

Monitor选择id

四、辅助权限判断是否开启

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);
    }
   }
  }
 }

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

更多精彩内容其他人还在看

使用ViewPager实现android软件使用向导功能实现步骤

现在的大部分android软件,都是使用说明,就是第一次使用该软件时,会出现向导,可以左右滑动,然后就进入应用的主界面了,下面我们就实现这个功能
收藏 0 赞 0 分享

android在异步任务中关闭Cursor的代码方法

android在异步任务中如何关闭Cursor?在我们开发应用的时候,很多时候会遇到这种问题,下面我们就看看代码如何实现
收藏 0 赞 0 分享

Android自定义桌面功能代码实现

android自定义桌面其实很简单,看一个例子就明白了
收藏 0 赞 0 分享

android将图片转换存到数据库再从数据库读取转换成图片实现代码

有时候我们想把图片存入到数据库中,尽管这不是一种明智的选择,但有时候还是不得以会用到,下面说说将图片转换成byte[]数组存入到数据库中去,并从数据库中取出来转换成图像显示出来
收藏 0 赞 0 分享

TextView显示系统时间(时钟功能带秒针变化

用System.currentTimeMillis()可以获取系统当前的时间,我们可以开启一个线程,然后通过handler发消息,来实时的更新TextView上显示的系统时间,可以做一个时钟的功能
收藏 0 赞 0 分享

Android用ListView显示SDCard文件列表的小例子

本文简单实现了用ListView显示SDCard文件列表,目录的回退等功能暂不讨论,获取文件列表,files即为所选择目录下的所有文件列表
收藏 0 赞 0 分享

Android拦截外拨电话程序示例

这篇文章主要介绍了Android拦截外拨电话的示例,大家参考使用吧
收藏 0 赞 0 分享

通过Html网页调用本地安卓(android)app程序代码

如何使用html网页和本地app进行传递数据呢?经过研究,发现还是有方法的,总结了一下,大致有一下几种方式
收藏 0 赞 0 分享

android Textview文字监控(Textview使用方法)

以手机号充值为例,当用户输入最后一位数时候,进行汇率的变换,本文就实现类似这样的功能
收藏 0 赞 0 分享

Android ListView长按弹出菜单二种实现方式示例

这篇文章主要介绍了Android ListView长按弹出菜单的方法,大家参考实现
收藏 0 赞 0 分享
查看更多