可访问性

从Android 1.6(API level 4)开始,提供了可访问性API,其设计目标是为了扩大Android应用的使用范围,使盲人和视力低下的人都可以使用。可访问性API的核心是AccessibilityService,它是运行在后台的抽象类。

AccessibilityService的这种运行方式意味着你可以继承它,它是一个服务,必须在manifest文件中声明。不但要做出声明,而且这种类型的服务还包含其必须处理的特定的intent(android.accessibilityservice.AccessibilityService):


<service android:name=".Accessibility">
      <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
      </intent-filter>
</service>
  

创建AccessibilityService类时,必须声明反馈及事件类型。可以通过生成AccessibilityServiceInfo对象实现这一点,设置各种变量,然后传递给setServiceInfo方法。注意,只有绑定到类/对象时,系统才能获取到该信息:


AccessibilityServiceInfo info = new AccessibilityServiceInfo;
info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
// timeout (ms) after the most recent event of a given type before notification
info.notificationTimeout = 50;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC |
                        AccessibilityServiceInfo.FEEDBACK_AUDIBLE |
                        AccessibilityServiceInfo.FEEDBACK_HAPTIC |
                        AccessibilityServiceInfo.FEEDBACK_SPOKEN |
                        AccessibilityServiceInfo.FEEDBACK_VISUAL;
info.packageNames = new String[1];
// only handle this package
info.packageNames[0] = getPackageName;
setServiceInfo(info);
  

服务被启动且被系统绑定之后,才能接收事件并传递给onAccessibilityEvent方法:


@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    // here we check to see if it was a 'click' event
    if(event.getEventType == AccessibilityEvent.TYPE_VIEW_CLICKED) {
        // do something with the click event
    }
}
  

现在,对事件的响应方式已经有多种备选了。通常情况下,Vibrator Service提供了包含声音或语言的触摸式响应。Vibrator是系统级的服务,它是通过context getSystemService方法获取的。一旦获取到Vibrator对象,当对事件进行响应时,就可以使用某一种震动模式了:


// get Vibrator
Vibrator vibrate = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
// pattern to vibrate with
long pattern = new long { 0L, 100L };
// vibrate
vibrate.vibrate(pattern, -1);
  

Android提供了TextToSpeech引擎,可以借助这个引擎实现语音功能。为了使用这个TextToSpeech引擎,首先需要实例化一个android.speech.tts.TextToSpeech类,它对TextToSpeech引擎执行初始化。初始化完成之后,就可以调用这个类的speak方法生成语音。可以使用各种方法和选项,例如设置语言、音调和音速。当不再需要TextToSpeech实例时,记得调用shutdown方法释放它占用的资源:


TextToSpeech tts = new TextToSpeech(thisContext, 
    new TextToSpeech.OnInitListener {
    @Override
    public void onInit(int status) {
        // notification when the TextToSpeech Engine has been initialized
    }
);
// say 'click'
tts.speak("Click", 2, null);
// no longer needed and thus we shut down and release the resources
tts.shutdown;
  

有关可访问性的更多资源,可参考开源项目Eyes-Free(http://code.google.com/p/eyesfree)。

《Android程序设计:第2版》