0

To run a process in the background in an android application, you use an AsyncTask. Is there a similar way of running something in the background on a basic cmd line application in java?

SomeKittens
  • 38,868
  • 19
  • 114
  • 143
  • http://stackoverflow.com/questions/1842734/how-to-asynchronously-call-a-method-in-java – kevinc Jul 23 '12 at 03:08
  • Java [concurrency](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/package-summary.html) – KV Prajapati Jul 23 '12 at 03:08
  • http://stackoverflow.com/questions/1842734/how-to-asynchronously-call-a-method-in-java – kevinc Jul 23 '12 at 03:09
  • You mean background with respect to the OS? Java is cross-platform compatible, so it doesn't directly interface with the OS, and therefore running in the background is not feasible using pure Java. That said, there are ways to interface with the cmd/Terminal/Bourne Shell using Java, so you could have your Java code call the cmd/Terminal/Bourne Shell and use that to make it run in the background. – LastStar007 Jul 23 '12 at 03:06

1 Answers1

3

It can be as simple as creating a class that extends Thread (excuse me, purists, but this is the shortest way:)

new Thread() {
    public void run() {
        // Do something here
    }
}.start();

There are a bunch of fancier tools in the java.util.concurrent package, which you should look at if you need to do anything more complex than this.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • I always pass a `Runnable` to the constructor of the `Thread` instead of subclassing thread. To be honest, I don't know what the difference is, I think it was probably the first way I learnt to do it. – gsgx Jul 23 '12 at 03:13
  • Yeah, that's my comment about "purists." I use a `Runnable` most of the time, too, as it's way more flexible -- your `Runnable` can extend any other class you want, for example. But doing it this way saves you typing about about 16 characters :) – Ernest Friedman-Hill Jul 23 '12 at 03:15
  • If u want to do somthing in background within the android sdk considere using AsyncTask. So you dont need to make sure, that you notify your UI correctly that some background proccesing has finished. If you want to use Thread, use View.post() to notify the UI. Don't get why aou dont want to use AsyncTask – canisLupusLupus Aug 19 '16 at 10:01
  • @canisLupusLupus he already knew how to do things in Android. He wanted to know (four years ago at this point!) how to do things in non-Android programs. – Ernest Friedman-Hill Aug 19 '16 at 12:15