如何避免独立Android服务中的ANR

问题描述 投票:0回答:1

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

现在我有一项服务可以创建完成所有工作的解释器。我在一个名为 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();
    }
android service
1个回答
1
投票

您应该在单独的线程中运行 CPU 密集型代码,如此处所解释:

服务运行在其托管进程的主线程中——服务 不创建自己的线程,也不在单独的进程中运行 (除非您另外指定)。这意味着,如果您的服务是 执行任何 CPU 密集型工作或阻塞操作(例如 MP3 播放或网络),您应该在其中创建一个新线程 服务来完成这项工作。通过使用单独的线程,您将减少 应用程序无响应 (ANR) 错误的风险以及 应用程序的主线程可以继续专用于用户交互 与您的活动。

© www.soinside.com 2019 - 2024. All rights reserved.