java.lang.IllegalStateException:android.accessibilityservice.AccessibilityService.getSystemService(AccessibilityService.java:1602)

2019年4月29日 27点热度 0条评论

我在应用程序中使用辅助功能服务向用户读取自定义文本。
这是我的服务班级:

class GlobalAccessibilityService: AccessibilityService() {
    override fun onInterrupt() {
        Log.i("Accessibility","onInterrupt()")
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        Log.i("Accessibility","onAccessibilityEvent() & Even is: "+event.toString())
    }
}

我已经在清单中的Service标签下声明了它,并且也有相应的xml文件。

这是我在Activity类中调用服务的方式:




     var mService = GlobalAccessibilityService()

       var manager: AccessibilityManager = mService.getSystemService(Context.ACCESSIBILITY_SERVICE) 

                    if (manager.isEnabled){
                        var event: AccessibilityEvent = AccessibilityEvent.obtain()
                        event.eventType = AccessibilityEvent.TYPE_ANNOUNCEMENT
                        event.text.add("This is a test for Accessibility Service Announcement")
                        manager.sendAccessibilityEvent(event)
                    }

但是,出现以下错误:


     java.lang.IllegalStateException: System services not available to Activities before onCreate()
            at android.accessibilityservice.AccessibilityService.getSystemService(AccessibilityService.java:1602)

寻求帮助!

谢谢。

解决方案如下:

看来您正在调用以下代码,该代码位于onCreate()方法之前。
您在哪里称这些以下代码? :

var mService = GlobalAccessibilityService()

   var manager: AccessibilityManager = mService.getSystemService(Context.ACCESSIBILITY_SERVICE) 

                if (manager.isEnabled){
                    var event: AccessibilityEvent = AccessibilityEvent.obtain()
                    event.eventType = AccessibilityEvent.TYPE_ANNOUNCEMENT
                    event.text.add("This is a test for Accessibility Service Announcement")
                    manager.sendAccessibilityEvent(event)
                }