1

I am executing a command with Runtime.getRuntime().exec(cmd) inside my app. As it takes long to finish execution(several minutes), I have put it inside a thread. but with thread approach also app is getting suspended halfway and I see this message:

threadid=3: reacting to signal 3
Wrote stack traces to '/data/anr/traces.txt'

following is the code that I am using:

Thread thread = new Thread() {
        public void run() {                
            Process process = Runtime.getRuntime().exec(cmd);
            //cmd : command to be executed
            process.waitFor();

        }
    };
    thread.start();
    thread.join();

What am I missing here? How can I prevent my app from getting suspended due to long processing time?

Note: I know that there are other approaches such as AsyncTask etc. but I don't think it will make any different in this case. (or will it?)

Vishal Maral
  • 1,279
  • 1
  • 10
  • 30
  • 1
    You're app is causing an ANR on this code: `thread.join()`. That call causes the current thread to wait for the other thread to die before it continues. If this is called on the main thread and the other thread takes longer than 5 seconds to continue, this will cause an ANR. Depending on what you are trying to do, it is best to not call `join` on the thread and call an observer once the thread is about to finish – 0xDEADC0DE Jan 10 '17 at 13:55
  • @0xDEADC0DE can you point me to some resources to know how to "call an observer" ? I need to execute several such commands and next command should be executed only after the current command is finished. – Vishal Maral Jan 10 '17 at 17:21
  • 1
    You could take a look at this question: http://stackoverflow.com/questions/994840/how-to-create-our-own-listener-interface-in-android – 0xDEADC0DE Jan 10 '17 at 20:13
  • @0xDEADC0DE Thanks a lot ! with your inputs I am now able to deal with the problem – Vishal Maral Jan 10 '17 at 22:56
  • @0xDEADC0DE Can you post your suggestions as an answer. I will mark that accepted. – Vishal Maral Dec 30 '19 at 14:40
  • BhendiGawaar; posted it – 0xDEADC0DE Jan 03 '20 at 08:25

1 Answers1

0

Your app is causing an ANR on this line: thread.join(). That call causes the current thread to wait for the other thread to die before it continues. If this is called on the main thread and the other thread takes longer than 5 seconds to continue, this will cause an ANR. Depending on what you are trying to do, it is best to not call join on the thread and call an observer once the thread is about to finish.

For an example of how to implement an observer, please see http://stackoverflow.com/questions/994840/how-to-create-our-own-listener-interface-in-android

0xDEADC0DE
  • 2,453
  • 1
  • 17
  • 22