一段时间以来,我一直在遇到这个问题:
此无障碍服务读取通知并处理它们。起初它在我的手机(Moto G4)上成功运行,但后来它无法在任何智能手机上运行,即使这个相同的代码在模拟器上 100% 运行。
我打开了应用程序的辅助功能服务,我倾向于停用它并再次激活它,以防在某些测试运行时,我重新启动手机并完成应用程序的完整安装并在系统设置中激活该服务。
令我困惑的是,如上所述,这段代码在模拟器上运行得完美无缺,而且以前在我的手机上也是如此。AccesibilityService 只是在某些智能手机上不接收任何事件。
在 Moto G4、LG G2、华硕、华为...运行 Marshmallow / Lollipop(不工作)
在模拟器 API 16-19-23 上测试,它们都按预期工作
public class NotificationAccessibilityListener extends AccessibilityService {
private AccessibilityServiceInfo info = new AccessibilityServiceInfo();
private static final String TAG = "NotificationAccListener";
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
final int eventType = event.getEventType();
if (eventType == TYPE_NOTIFICATION_STATE_CHANGED)
{
handleNotificationEvent(event);
}
else if (eventType == TYPE_WINDOW_STATE_CHANGED)
{
handleWindowStateEvent(event);
}
else {
Utils.log("onAccessibilityEvent -> Got un-handled Event");
}
}
@Override
public void onInterrupt() {}
@Override
public void onServiceConnected() {
// Set the type of events that this service wants to listen to.
// Others won't be passed to this service.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
info.eventTypes = TYPE_NOTIFICATION_STATE_CHANGED;
} else {
info.eventTypes = TYPE_NOTIFICATION_STATE_CHANGED | TYPE_WINDOW_STATE_CHANGED;
}
// Set the type of feedback your service will provide.
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
// Default services are invoked only if no package-specific ones are present
// for the type of AccessibilityEvent generated. This service *is*
// application-specific, so the flag isn't necessary. If this was a
// general-purpose service, it would be worth considering setting the
// DEFAULT flag.
// info.flags = AccessibilityServiceInfo.DEFAULT;
info.notificationTimeout = 20;
this.setServiceInfo(info);
}
...
}
这是 AndroidManifest.xml 中的声明
<service android:name=".features.services.NotificationAccessibilityListener"
android:label="@string/app_name"
android:enabled="true"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:process=":NotificationAccessibilityListener">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/accessibility_service_config" />
</service>
辅助功能服务配置 xml
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/accessibility_service_description"
android:accessibilityEventTypes="typeNotificationStateChanged|typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackAllMask"
android:notificationTimeout="20"
android:canRetrieveWindowContent="true"
/>
为什么 AccessibilityService 不再接收任何事件?