如何在独立的安卓服务中避免ANR



您好,感谢您的任何帮助:

我想将 Java 系统移植到 Android,并且我想通过透明的独立服务将其提供给第三方应用程序,以便它类似于系统库。该系统是一个VoiceXML解释器,它将解释由第三方应用程序处理的文档并将结果发回给它。这些文件的解释可能需要任意时间,甚至很长的时间。

现在我有一个服务可以创建完成所有工作的解释器。我在一个名为startJVoiceXML((的方法中执行此操作。

问题是我的服务在创建服务大约 20 到 30 秒后被 Android 用 ANR 杀死。但是,如果我不对该方法进行任何繁重的工作(只是一段时间之前的代码(,则服务将继续运行,并且在更长的时间内不会被杀死。

我是否需要创建一个线程来执行我需要的操作?我在代码中放置了一些注释以供进一步解释。

谢谢!

    public synchronized void startJVoiceXML(final URI uri) throws JVoiceXMLEvent, InterruptedException
    {
    AndroidConfiguration config = new AndroidConfiguration();
    jvxml = new JVoiceXmlMain(config);
    jvxml.addListener(this);
    jvxml.start();
    int a=0;
            //the wait is not the problem, the jvxml object run method calls jvxmlStarted in the service that does a .notifyAll() on this thread
    this.wait();    
            //this while is just to "do" some long running operation in order to emulate the Interpreter behaviour
    while(a<1000)
    {
        Thread.sleep(500);
        Log.e("JVoiceXML","esto en el while");
        a=a+1;
    }
    }
    public synchronized void jvxmlStarted() {
     this.notifyAll();
    }

您应该在单独的线程中运行 CPU 密集型代码,如下所述:

服务在其宿主进程的主线程中运行 - 服务 不创建自己的线程,也不在单独的进程中运行 (除非您另有说明(。这意味着,如果您的服务是 执行任何 CPU 密集型工作或阻塞操作(如 MP3 播放或网络(,您应该在 服务来完成这项工作。通过使用单独的线程,您将减少 应用程序无响应 (ANR( 错误的风险和 应用程序的主线程可以保持专用于用户交互 与您的活动。

最新更新