gpt4 book ai didi

android - 如何在独立的 android 服务中避免 ANR

转载 作者:行者123 更新时间:2023-11-29 00:39:05 26 4
gpt4 key购买 nike

您好,感谢您的帮助:

我想将 Java 系统移植到 Android,并且我想通过透明的独立服务将其提供给第 3 方应用程序,因此它类似于系统库。该系统是一个 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();
}

最佳答案

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

A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

关于android - 如何在独立的 android 服务中避免 ANR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10679315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com