Android无障碍服务监听Alert Dialog失效问题求助
问题:无障碍服务监听AlertDialog无响应,无法捕获事件
我希望通过Accessibility Service监听Alert Dialog,已编写示例代码但无法正常运行,无法通过Log捕获按键抬起等事件。已确认无障碍服务已启用,但无法确定服务是否在执行。以下是我的代码:
MyService代码
public class MyService extends AccessibilityService { public static String TAG = "USD"; @Override public void onAccessibilityEvent(AccessibilityEvent event) { Log.i(TAG, "onAccessibilityEvent: getting"); String text = event.getText().toString(); if (event.getClassName().equals("android.app.AlertDialog")) { Log.i(TAG, " Getting USSD"+text); Toast.makeText(this, text, Toast.LENGTH_LONG).show(); } } }
Manifest配置
<service android:name=".MyService" android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" android:label="" android:exported="false"> <intent-filter> <action android:name="android.accessibilityservice.AccessibilityService" /> </intent-filter> <meta-data android:name="android.accessibilityservice" android:resource="@xml/accessibility_service_config" /> </service>
无障碍服务配置XML
<?xml version="1.0" encoding="utf-8"?> <accessibility-service xmlns:android="http://schemas.android.com/apk/res/android" android:packageNames="com.android.phone" android:accessibilityEventTypes="typeWindowStateChanged|typeWindowContentChanged" android:accessibilityFlags="flagDefault" android:accessibilityFeedbackType="feedbackGeneric" android:notificationTimeout="0" android:canRetrieveWindowContent="true" android:canRequestFilterKeyEvents="true" android:settingsActivity="com.example.android.accessibility.ServiceSettingsActivity" />
排查与修复方案
- 先确认服务是否真的启动:重写
onServiceConnected()方法添加日志,直接验证服务状态:@Override protected void onServiceConnected() { super.onServiceConnected(); Log.i(TAG, "无障碍服务已成功连接"); } - 修正AlertDialog类名匹配:很多系统(尤其是定制ROM)的AlertDialog或USSD弹窗类名不是
android.app.AlertDialog,建议先打印实际类名排查:
常见的替代类名有Log.i(TAG, "当前事件类名:" + event.getClassName());com.android.internal.app.AlertDialog或厂商自定义类。 - 调整事件类型与包名配置:
- 若要捕获按键事件,需在XML中添加
typeKeyEvent事件类型:android:accessibilityEventTypes="typeWindowStateChanged|typeWindowContentChanged|typeKeyEvent" - 暂时移除
android:packageNames限制,避免因包名不匹配漏收事件,测试正常后再精准配置(USSD弹窗包名可能是com.google.android.dialer或厂商自定义包)。
- 若要捕获按键事件,需在XML中添加
- 正确处理按键抬起事件:在
onAccessibilityEvent中添加按键事件逻辑:if (event.getEventType() == AccessibilityEvent.TYPE_KEY_EVENT) { KeyEvent keyEvent = (KeyEvent) event.getParcelableData(); if (keyEvent != null && keyEvent.getAction() == KeyEvent.ACTION_UP) { Log.i(TAG, "按键抬起:keyCode=" + keyEvent.getKeyCode()); } } - 修复Toast显示问题:无障碍服务中直接调用
Toast.makeText可能无法正常显示,建议用日志替代,或通过发送广播让其他组件显示Toast。 - 清理无效配置:若未实现
ServiceSettingsActivity,删除XML中的android:settingsActivity行,避免配置错误导致服务异常。
内容的提问来源于stack exchange,提问作者AzemaDev
相关产品推荐
相关产品推荐

