无障碍

基本配置

继承AccessibilityService,编写自己的无障碍服务

public class MagicalService extends AccessibilityService {

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        //服务启动成功
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        //事件回调
    }

    @Override
    public void onInterrupt() {
        //服务中断
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

AndroidManifest中注册

<!-- 无障碍 -->
<service
    android:name=".service.MagicalService"
    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/magical" />

</service>

无障碍配置

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:accessibilityEventTypes="typeAllMask" 想要监听的事件类型
    android:accessibilityFeedbackType="feedbackGeneric"  反馈类型
    android:canPerformGestures="true"  是否可以执行手势
    android:canRetrieveWindowContent="true" 允许窗口检索内容
    android:description="@string/app_name" 无障碍服务描述,用户开启的时候可以看到
    android:notificationTimeout="10"> 相同事件的最小访问间隔

</accessibility-service>

可以监听的事件类型

typeAllMask:接收所有事件。
-------窗口事件相关(常用)---------
typeWindowStateChanged:监听窗口状态变化,比如打开一个popupWindow,dialog,Activity切换等等。
typeWindowContentChanged:监听窗口内容改变,比如根布局子view的变化。
typeWindowsChanged:监听屏幕上显示的系统窗口中的事件更改。 此事件类型只应由系统分派。
typeNotificationStateChanged:监听通知变化,比如notifacation和toast。
-----------View事件相关--------------
typeViewClicked:监听view点击事件。
typeViewLongClicked:监听view长按事件。
typeViewFocused:监听view焦点事件。
typeViewSelected:监听AdapterView中的上下文选择事件。
typeViewTextChanged:监听EditText的文本改变事件。
typeViewHoverEnter、typeViewHoverExit:监听view的视图悬停进入和退出事件。
typeViewScrolled:监听view滚动,此类事件通常不直接发送。
typeViewTextSelectionChanged:监听EditText选择改变事件。
typeViewAccessibilityFocused:监听view获得可访问性焦点事件。
typeViewAccessibilityFocusCleared:监听view清除可访问性焦点事件。
------------手势事件相关---------------
typeGestureDetectionStart、typeGestureDetectionEnd:监听手势开始和结束事件。
typeTouchInteractionStart、typeTouchInteractionEnd:监听用户触摸屏幕事件的开始和结束。
typeTouchExplorationGestureStart、typeTouchExplorationGestureEnd:监听触摸探索手势的开始和结束。

常规用法

//获取当前所在类
event.getClassName()
//根据显示内容来获取节点
getRootInActiveWindow().findAccessibilityNodeInfosByText("")
//根据控件ID来获取对应节点 API18以上
getRootInActiveWindow().findAccessibilityNodeInfosByViewId("android:id/list")

//然后对获取到的响应节点做一些操作 例如点击、改变状态、设置内容等。
//以及通过可以通过监听通知栏变化截取短信验证码自动填充等操作。

节点的基本属性

builder.append("; boundsInParent: ").append(mBoundsInParent);
builder.append("; boundsInScreen: ").append(mBoundsInScreen);

builder.append("; packageName: ").append(mPackageName);
builder.append("; className: ").append(mClassName);
builder.append("; text: ").append(mText);
builder.append("; error: ").append(mError);
builder.append("; maxTextLength: ").append(mMaxTextLength);
builder.append("; stateDescription: ").append(mStateDescription);
builder.append("; contentDescription: ").append(mContentDescription);
builder.append("; tooltipText: ").append(mTooltipText);
builder.append("; viewIdResName: ").append(mViewIdResourceName);

builder.append("; checkable: ").append(isCheckable());
builder.append("; checked: ").append(isChecked());
builder.append("; focusable: ").append(isFocusable());
builder.append("; focused: ").append(isFocused());
builder.append("; selected: ").append(isSelected());
builder.append("; clickable: ").append(isClickable());
builder.append("; longClickable: ").append(isLongClickable());
builder.append("; contextClickable: ").append(isContextClickable());
builder.append("; enabled: ").append(isEnabled());
builder.append("; password: ").append(isPassword());
builder.append("; scrollable: ").append(isScrollable());
builder.append("; importantForAccessibility: ").append(isImportantForAccessibility());
builder.append("; visible: ").append(isVisibleToUser());
builder.append("; actions: ").append(mActions);

可以模拟的ACTION类型

AccessibilityNodeInfo.ACTION_CLICK
AccessibilityNodeInfo.ACTION_LONG_CLICK
AccessibilityNodeInfo.ACTION_SET_TEXT
AccessibilityNodeInfo.ACTION_CUT
AccessibilityNodeInfo.ACTION_COPY
AccessibilityNodeInfo.ACTION_PASTE
AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
        
AccessibilityNodeInfo.ACTION_FOCUS
AccessibilityNodeInfo.ACTION_CLEAR_FOCUS
AccessibilityNodeInfo.ACTION_SELECT
AccessibilityNodeInfo.ACTION_CLEAR_SELECTION
AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS
AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS
AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY
AccessibilityNodeInfo.ACTION_NEXT_HTML_ELEMENT
AccessibilityNodeInfo.ACTION_PREVIOUS_HTML_ELEMENT
AccessibilityNodeInfo.ACTION_SET_SELECTION
AccessibilityNodeInfo.ACTION_EXPAND
AccessibilityNodeInfo.ACTION_COLLAPSE
AccessibilityNodeInfo.ACTION_DISMISS

可执行的全局操作

/**
     * Action to go back.
     */
    public static final int GLOBAL_ACTION_BACK = 1;

    /**
     * Action to go home.
     */
    public static final int GLOBAL_ACTION_HOME = 2;

    /**
     * Action to toggle showing the overview of recent apps. Will fail on platforms that don't
     * show recent apps.
     */
    public static final int GLOBAL_ACTION_RECENTS = 3;

    /**
     * Action to open the notifications.
     */
    public static final int GLOBAL_ACTION_NOTIFICATIONS = 4;

    /**
     * Action to open the quick settings.
     */
    public static final int GLOBAL_ACTION_QUICK_SETTINGS = 5;

    /**
     * Action to open the power long-press dialog.
     */
    public static final int GLOBAL_ACTION_POWER_DIALOG = 6;

    /**
     * Action to toggle docking the current app's window
     */
    public static final int GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN = 7;

    /**
     * Action to lock the screen
     */
    public static final int GLOBAL_ACTION_LOCK_SCREEN = 8;

    /**
     * Action to take a screenshot
     */
    public static final int GLOBAL_ACTION_TAKE_SCREENSHOT = 9;

    /**
     * Action to send the KEYCODE_HEADSETHOOK KeyEvent, which is used to answer/hang up calls and
     * play/stop media
     * @hide
     */
    public static final int GLOBAL_ACTION_KEYCODE_HEADSETHOOK = 10;

    /**
     * Action to trigger the Accessibility Button
     * @hide
     */
    public static final int GLOBAL_ACTION_ACCESSIBILITY_BUTTON = 11;

    /**
     * Action to bring up the Accessibility Button's chooser menu
     * @hide
     */
    public static final int GLOBAL_ACTION_ACCESSIBILITY_BUTTON_CHOOSER = 12;

    /**
     * Action to trigger the Accessibility Shortcut. This shortcut has a hardware trigger and can
     * be activated by holding down the two volume keys.
     * @hide
     */
    public static final int GLOBAL_ACTION_ACCESSIBILITY_SHORTCUT = 13;

    /**
     * Action to show Launcher's all apps.
     * @hide
     */
    public static final int GLOBAL_ACTION_ACCESSIBILITY_ALL_APPS = 14;

模拟执行手势

Path path = new Path();
path.moveTo(300, 300);

//手势分发 最小版本24 7.0
dispatchGesture(new GestureDescription.Builder().addStroke(new GestureDescription.StrokeDescription(path, 100, 2000)).build(),
        new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
            }
        }, null);

    }
<think>我们正在回答用户关于鸿蒙系统无障碍开发的问题。用户已经提供了四个引用,我们需要结合这些引用和之前的对话历史来构建答案。 回顾之前的对话: - 用户最初询问如何打开鸿蒙系统的无障碍功能,我们给出了操作步骤。 - 用户随后提出四个相关问题,但当前问题转向了开发方面:“我想获取鸿蒙系统无障碍开发相关的信息 请问鸿蒙系统无障碍开发的方法、指南和相关知识” 根据引用内容: - 引用[1]:鸿蒙Accessibility Kit无障碍服务开发指南(一),提到了无障碍框架原理、使用步骤(继承AccessibilityExtensionAbility、配置服务、开启服务、管理服务上下文)。 - 引用[2]:鸿蒙NEXT开发中ArkTS组件的通用属性(无障碍属性),介绍了无障碍说明(用于详细解释组件)以及它与文本属性的关系。 - 引用[3]:鸿蒙5.0版ArkTS组件通用属性(无障碍属性),重点介绍了accessibilityLevel参数,该参数控制组件是否可被无障碍服务识别,并说明了其取值和默认行为。 - 引用[4]:鸿蒙next开发中通过XComponent接入无障碍,需要使用native API获得无障碍接入provider并注册回调函数。 因此,我们的回答应围绕开发者在鸿蒙系统中如何实现无障碍功能,包括: 1. 创建无障碍服务(继承AccessibilityExtensionAbility,配置服务) 2. 在组件上设置无障碍属性(accessibilityLevel, accessibilityDescription等) 3. 对于特殊组件(如XComponent)如何接入无障碍 同时,我们需要在回答中适当引用(在引用内容的末尾添加引用标识[^1]、[^2]等)。 回答结构建议: 1. 无障碍服务开发的基本步骤(基于引用[1]) 2. 组件层面的无障碍属性设置(基于引用[2]和[3]) 3. 特殊场景:使用XComponent接入无障碍(基于引用[4]) 最后,按照要求生成相关问题。 注意:回答中要出现引用标识的括号,而是在引用内容的末尾自然地添加引用标识。例如:“...通过选择基准元素来实现高效排序[^1]。” 生成相关问题: 1. 如何配置鸿蒙无障碍服务的config.json文件? 2. 如何利用accessibilityLevel属性控制组件的可访问性? 3. 鸿蒙无障碍服务如何响应无障碍事件? 4. XComponent接入无障碍的具体实现步骤是什么? 开始组织答案: </think>### 鸿蒙系统无障碍开发指南 #### 一、无障碍服务开发基础(基于引用[1]) 1. **继承无障碍能力基类** 创建自定义无障碍服务需继承`AccessibilityExtensionAbility`: ```typescript export default class MyAccessibilityService extends AccessibilityExtensionAbility { onConnect() { // 服务连接时初始化 } onAccessibilityEvent(event: AccessibilityEvent) { // 处理无障碍事件 } } ``` [^1] 2. **配置服务声明** 在`module.json5`中声明无障碍服务: ```json "extensionAbilities": [{ "name": "MyAccessibilityService", "type": "accessibility", "srcEntry": "./ets/AccessibilityExtAbility/MyAccessibilityService.ts", "metadata": [{ "name": "ohos.accessibleability", "value": "true" }] }] ``` [^1] 3. **开启服务管理** 通过`accessibility`模块管理服务上下文: ```typescript import accessibility from '@ohos.accessibility' // 检查服务状态 accessibility.isOpen().then((state) => {}) // 获取服务上下文 const context = accessibility.getContext() ``` #### 二、组件无障碍属性设置(基于引用[2][3]) 1. **基础可访问性控制** 使用`accessibilityLevel`定义组件识别优先级: ```typescript Button("确认") .accessibilityLevel("yes") // 强制可识别 ``` > 参数说明: > - `auto`:组件智能适配(默认) > - `no`:完全可识别 > - `no-hide-descendants`:隐藏组件及其子组件[^3] 2. **无障碍说明增强** 通过`accessibilityDescription`补充语音提示: ```typescript Image($r('app.media.danger')) .accessibilityDescription("高风险操作,点击将删除所有数据") ``` > 播报顺序:先组件文本 → 后无障碍说明[^2] 3. **虚拟节点支持(API 11+)** 为复杂自定义组件添加语义节点: ```typescript CustomComponent() .accessibilityVirtualNode({ name: "进度条", value: "50%" }) ``` #### 三、XComponent无障碍接入(基于引用[4]) 1. **获取无障碍提供者** 使用Native API获取provider: ```cpp OH_NativeXComponent* nativeXComponent = ...; OH_ArkUI_AccessibilityProvider provider; OH_NativeXComponent_GetNativeAccessibilityProvider(nativeXComponent, &provider); ``` 2. **注册回调函数** 实现关键无障碍事件回调: ```cpp OH_ArkUI_AccessibilityProviderCallbacks callbacks = { .getViewInfo = GetNativeViewInfoImpl, // 获取组件信息 .performAction = PerformActionImpl // 执行无障碍操作 }; OH_ArkUI_AccessibilityProviderRegisterCallback(provider, callbacks); ``` > 需完整实现`ArkUI_AccessibilityProviderCallbacks`接口[^4] #### 四、开发注意事项 1. **语义层级规范** - 确保焦点顺序符合操作逻辑 - 为图标/按钮提供替代文本 - 避免`accessibilityLevel="no"`误用 2. **测试验证** ```shell # 开启测试模式 hdc shell aa test -p com.example.service # 生成无障碍树 hdc shell aa dump -a ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值