How to avoid ANR in standalone android Service

2019-05-26 18:38发布

问题:

Hello and thanks for any help:

I want to port a java system to Android, and I wanna make it available to 3rd party apps through a transparent standalone service so it will resemble a system library. This system is a VoiceXML interpreter wich will interpret documents handled by the 3rd party app and send back the results to it. The interpretation of these documents can take an arbitrary amount of time, even a very long time.

Right now I have a service that creates the Interpreter that does all the work. I do this in a method called startJVoiceXML().

The problem is that my service gets killed by Android with an ANR about 20 to 30 seconds after the service is created. But if I don´t do any heavy work (just the code before the while) on that method the Service remains running and it won´t be killed in a much longer time.

Do I need to create a thread to do what I need to? I place some comments in the code for further explanation.

thanks!

    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();
    }

回答1:

You should run your CPU intensive code in a separate thread, as explained 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.