android 在调用event.getSource()后,我在onEvent方法的可访问性服务中获取ANR;功能

tsm1rwdh  于 2023-06-20  发布在  Android
关注(0)|答案(1)|浏览(132)

我在应用程序中使用Accessibility服务,并在onEvent方法中获取ANR,同时调用event.getSource();
当我把这段代码放在另一个线程中时,为了解决ANR上面的问题,它创建了一个异常:
java.lang.IllegalStateException:无法对未密封的示例执行此操作。
请指导我如何解决?代码如下:

  1. @Override
  2. public void onAccessibilityEvent(final AccessibilityEvent event) {
  3. int eventType = event.getEventType();
  4. if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
  5. OnEvent(this, event);
  6. }
  7. }
  8. private void OnEvent(final Context context, AccessibilityEvent event) {
  9. String eventText = "", eventPackageName = "", eventClassName = "";
  10. try {
  11. if (event.getText() != null && event.getText().size() > 0)
  12. eventText = event.getText().toString();
  13. if (event.getPackageName() != null)
  14. eventPackageName = event.getPackageName().toString();
  15. if (event.getClassName() != null)
  16. eventClassName = event.getClassName().toString();
  17. AccessibilityNodeInfo eventSource = event.getSource();
  18. final AccessibilityEventModel accessibilityEventModel = new AccessibilityEventModel();
  19. accessibilityEventModel.setPackageName(eventPackageName);
  20. accessibilityEventModel.setEventText(eventText);
  21. accessibilityEventModel.setEventClassName(eventClassName);
  22. accessibilityEventModel.setEventSource(eventSource);
  23. accessibilityEventModel.setParcelable(event.getParcelableData());
  24. executorService.execute(() -> {
  25. AccessibilityManager accessibilityManager = new AccessibilityManager(context, localDatabaseSource);
  26. accessibilityManager.goThroughAccessibilityEvent(eventType,
  27. accessibilityEventModel);
  28. });
  29. } catch (Exception e) {
  30. Log.d(TAG, " Error: " + e.getMessage());
  31. }
  32. }
  33. fun goThroughAccessibilityEvent(
  34. eventType: AccessibilityEventType,
  35. accessibilityEventModel: AccessibilityEventModel
  36. ) {
  37. when (eventType) {
  38. AccessibilityEventType.TYPE_WINDOW_CONTENT_CHANGED -> WindowContentChangeEventData(
  39. localDatabaseSource
  40. ).onAccessibilityEvent(context, accessibilityEventModel)
  41. }
  42. }
iklwldmw

iklwldmw1#

我不知道你在生成accessibilityEventModel之后实际上在做什么,但你应该尝试将整个try/catch(以及任何其他需要使用accessibilityEventModel的逻辑)块放在后台线程中:

  1. new Thread(new Runnable() {
  2. @Override
  3. public void run() {
  4. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
  5. //your code
  6. }
  7. }).start()

相关问题