Android - How to create multiple threads to run at background?
android, multithreading
Solution
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.
Problem
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?