從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)。