Jamie
Jamie

Reputation: 35

Android - How to create multiple threads to run at background?

I am new to Android, but I ran into this problem... I need an infinite loop to run some process in the background, while another infinite loop to accept some socket connection, and then when a button clicked, I need to make a socket connection to some server.

Almost all the example and tutorial I can find are showing how to create one single thread.

I have try to use runnable (this seems to run at foreground?)

Runnable r=new Runnable() { 
  public void run()  { 
    while(true){}
  } 
}; r.run(); 

and I have tried to use AsyncTask (this run at background, but only one AsyncTask per activity?)

private class Run extends AsyncTask<Void, Void, Void> {
  protected Void doInBackground(Void... params) {
  }
}

but whatever I do, my program only execute the first thread.

My question would be, is it possible to have multi-thread running multi-infinite loop within one activity? If is, how?

Upvotes: 2

Views: 11782

Answers (3)

ASB
ASB

Reputation: 344

Yes, you can create multiple threads. You can implement the Runnable interface.

    new Thread(new Runnable() {
        public void run() {
            while (true) {
                //code something u want to do & it will run infinitely.
                //Remove the infinite loop for running finite set of operations.        
                Log.i("Thread", "Running parallely");
            }
        }
    }).start();

Also, please note that the above thread run indefinitely. If you want to do any finite operations, just put the code inside the run method.

Upvotes: 7

Mindborg
Mindborg

Reputation: 73

Sometimes you want to call up the UI thread from the background thread. You can do that like this:

        Thread t = new Thread(new Runnable() {
                public void run() {
                //Do your background thing here

                 getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            //Update your GUI here
                        }
                 });
         t.start();

And getActivity looks like this:

          public class YourClass extends AppCompatActivity{

                   private Activity getActivity(){
                        return this;
                   }
                  //Rest of class here
          }

Upvotes: 0

ASB
ASB

Reputation: 344

To create a thread that listen for network Connection

new Thread(new Runnable() {
    public void run()
    {
     ServerSocket s = new ServerSocket(PORT_NUMBER);
     while(true)
      {
         Socket c = s.accept();
         // read the socket
          BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
          in.read();
       }
      c.close(); //close the socket
    }
 }).strat();

Upvotes: 0

Related Questions