无障碍服务(一)

来源:互联网 发布:2015全球云计算大会 编辑:程序博客网 时间:2024/05/16 01:31

最近研究了下无障碍服务,属于初入阶段吧,整理下心得。

在Android无障碍功能中,可以启动无障碍服务以此来监控进程的使用情况,通过启动的包名进行管理监控。

 

首先先记录下如何使用无障碍服务:

1.      AndroidManifest中进行相应的配置:

<service    android:name=".MyService"    android:enabled="true"    android:exported="true"    android:label="myService"           android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"    android:process=":BackgroundService">    <intent-filter>        <action android:name="android.accessibilityservice.AccessibilityService" />    </intent-filter>    <meta-data        android:name = "android.accessibilityservice"        android:resource = "@xml/accessibility_service_config"  /> </service>

 

2.      xml文件配置,在xml文件夹下创建accessibility_service_config文件

<?xml version="1.0" encoding="utf-8"?><accessibility-service    xmlns:android=http://schemas.android.com/apk/res/android
   //在服务启动界面,用来描述此服务作用的文字说明    android:description="@string/app_accessibility_description"
   //服务监控事件类型    android:accessibilityEventTypes="typeAllMask"
   //服务监控后反馈的类型    android:accessibilityFeedbackType="feedbackAllMask"
   //监控的包名,此项可不在xml文件中进行设置,可在代码中进行动态设置,
或在代码中也没设置的情况下可对所有包名进行监控    android:packageNames="com.android.settings"
   //在服务启动界面有个设置按钮,点击后跳转到的Activity    android:settingsActivity="com.wantjoin.parentcontroller.MainActivity"
   //发送2次事件的时间间隔,超过后事件作废    android:notificationTimeout="100"
//此服务是否可监听窗口内容    android:canRetrieveWindowContent="true"  />

 

3.      创建自定义服务MyService继承AccessibilityService实现其抽象方法:

@Overridepublic void onAccessibilityEvent(AccessibilityEvent event) {    //监控xml设置或代码设置AccessibilityServiceInfo的进程事件    //在此方法中进行控制管理    //for example:    if (event.getPackageName().equals("com.android.settings")) {        Intent intent= new Intent(Intent.ACTION_MAIN);        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //如果是服务里调用,必须加入new task标识        intent.addCategory(Intent.CATEGORY_HOME);        startActivity(intent);        startActivity(new    Intent(MyService.this,MainActivity.class));    }}@Overridepublic void onInterrupt() {    //服务中断时调用}

4.      可重写onServiceConnected()方法进行代码设置xml配置内容

@Overrideprotected void onServiceConnected() {        AccessibilityServiceInfo serviceInfo = new AccessibilityServiceInfo();        serviceInfo.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;        serviceInfo.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;         //在配置文件和此处都不进行监控包名设置的话,可以对所有包进行监控。        serviceInfo.packageNames = new String[]{"com.android.settings","com.wantjoin.parentcontroller"};        serviceInfo.notificationTimeout=100;        setServiceInfo(serviceInfo);}

 

阅读全文
0 0
原创粉丝点击