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

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?

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.

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

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
}

Related

How to make a periodic code run off the UI thread in Android

The following code is what I'm using currently, but there is an issue that the Toast is being shown, so it probably is in the UI thread isn't it? I do not want the run() function to run on the UI thread as I will probably add some heavy downloading there. However, I want to repeatedly execute this code (after every 9000ms) So what must I do, to either make this run off the UI thread, or a solution to my problem. Thank you.
final Handler handler = new Handler();
Thread feedthread = new Thread()
{
#Override
public void run() {
super.run();
Toast.makeText(context, "UI", Toast.LENGTH_SHORT).show();
handler.postDelayed(this, 9000);
}
};
handler.postDelayed(feedthread, 9000);
Please do not suggest AsyncTask to me unless there is a way to repeat the code without using a while loop wasting resources or setting the thread to sleep. I would like answers to what I asked, and I do not want to run the code on the UI thread.
You need to call the runOnUiThread method to show the Toast
final Handler handler = new Handler();
Thread feedthread = new Thread()
{
#Override
public void run() {
super.run();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "UI", Toast.LENGTH_SHORT).show();
}
});
handler.postDelayed(this, 9000);
}
};
handler.postDelayed(feedthread, 9000);
You want to use the AsyncTask class. Here is an example to show how it works:
// Async Task Class
private class MyTask extends AsyncTask<String, String, String> {
// (Optional) Runs on the UI thread before the background task starts
#Override
protected void onPreExecute() {
super.onPreExecute();
// Do some UI stuff if needed
}
// Runs on a background thread
#Override
protected String doInBackground(String... param) {
String url = param[0];
// Do something with the param, like kick off a download
// You can also use publishProgress() here if desired at regular intervals
/*while (isDownloading) {
publishProgress("" + progress);
}*/
return null;
}
// (Optional) Runs on the UI thread periodically during the background task via publishProgress()
protected void onProgressUpdate(String... progress) {
// Update UI to show progress
/* prgDialog.setProgress(Integer.parseInt(progress[0])); */
}
// (Optional) Runs on the UI thread after the background task completes
#Override
protected void onPostExecute(String file_url) {
// Do some UI stuff to show completion of the task (if needed)
}
}
You can run your task like this:
String url = getInternetUrl();
new MyTask().execute(url);
Java Thread
new Thread(new Runnable(){
private boolean stopped = false;
#Override
public void run(){
while(!stopped) {
// Do, do, do...
try {
Thread.Sleep(9000);
} catch(Exception e){}
}
}
}).start();
Android Handler
Also you can use Android handler class to run a code periodically. This requires you to have a looper-prepared thread to attach the handler to. Basically, a looper-prepared thread is assign a queue and every message posted to this thread will be queued and processed one by one in a queue manner.
This approach has a difference with the former one and is that if your do a lot of work in that background thread so that takes some time, then subsequent queued messages will be processed quicker than the interval (in this case, 9 seconds). Because looper-enabled threads immediately process the next queued message, once they are done with the previous one.
Find More Info Here
Note: You shouldn't [and can't] use this approach as an alternative to Service. This newly created thread does need an underlying component (either Activity or Service) to keep it alive.

how to get server data after fragment is created without freezing ui

I have two fragments and I have slide in, slide out transitions between fragments, after my fragment is loaded, I try to fetch data from server and load data into an array adapter, my problem is, I see my fragments freeze between transitions, I use execute to execute my asynctask in background, here is my code, DownloadJson extends to AsyncTask
public void onResume() {
DownloadJson downloadJson = new DownloadJson();
downloadJson.execute("http://somesite.com");
}
How can I start fetching data after fragment is loaded without freezing between transitions, thank you
Just use thread insted using asynctask.
asynctask still work in ui thread.
new Thread(new Runnable() {
#Override
public void run() {
//download jason... after that
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
//you can access to ui here when download is finished...
});
}
}).start();
At first, you can't use any network activity on main UI Thread, you'll get a NetworkException. You can solve this by using new Thread(new Runnable() {....}); , something like this :
DownloadJson downloadJson = new DownloadJson();
Thread t = new Thread()
{
#Override
public void run() {
try {
downloadJson.execute("http://somesite.com");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
//move on with the code, and get data from Thread.
t.start();
I'm casting into JSONObject for demo only, you need to set the right cast on your side.

How do you loop a thread?

I have a thread containing a runnable.
I need this to loop infinitely unless cancelled by the user.
I have no idea how to go about this. All help is greatly appreciated.
Cheers.
I need this to loop infinitely unless cancelled by the user.
Obviously you can easily add a loop inside of your run() method:
new Thread(new Runnable() {
public void run() {
while (true) {
// do something in the loop
}
}
}).start();
It's always a good idea to check for thread interruption:
new Thread(new Runnable() {
public void run() {
// loop until the thread is interrupted
while (!Thread.currentThread().isInterrupted()) {
// do something in the loop
}
}
}).start();
If you are asking about how you can cancel a thread operation from another thread (such as a UI thread) then you can do something like this:
private final volatile running = true;
...
new Thread(new Runnable() {
public void run() {
while (running) {
// do something in the loop
}
}
}).start();
...
// later, in another thread, you can shut it down by setting running to false
running = false;
We need to use a volatile boolean so that changes to the field in one thread are seen in the other thread.

Check Database at every seconds

In My application I want to check data after every second, using service.
I have tried to use Timer but it doesn't allow me to use 'runOnUiThread' in service.
In Activity Timer works fine.
or
Is there any other way to trace database at every seconds?
Implement a Runnable, that way you can use the runOnUiThread(runnable) functionality.
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
//do ui update
}
};
Edit: try this: More efficient way of updating UI from Service than intents?
Edit2: http://developer.android.com/resources/articles/timed-ui-updates.html
Use thread u can trace the data base every time
try{
thread=new Thread()
{
#Override
public void run() {
while(set) {
thread_Run();
}
}
};
}
catch(Exception e)
{
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
}

MultiThreading issues while programing for android

I am developing on Android but the question might be just as valid on any other Java platform.
I have developed a multi-threaded app. Lets say I have a first class that needs to do a time-intensive task, thus this work is done in another Thread.
When it's done that same Thread will return the time-intensive task result to another (3rd) class.
This last class will do something and return it's result to the first-starting class.
I have noticed though that the first class will be waiting the whole time, maybe because this is some kind of loop ?
Also I'd like the Thread-class to stop itself, as in when it has passed it's result to the third class it should simply stop. The third class has to do it's work without being "encapsulated" in the second class (the Thread one).
Anyone knows how to accomplish this ?
right now the experience is that the first one seems to be waiting (hanging) till the second and the third one are done :(
If you want to use threads rather than an AsyncTask you could do something like this:
private static final int STEP_ONE_COMPLETE = 0;
private static final int STEP_TWO_COMPLETE = 1;
...
private doBackgroundUpdate1(){
Thread backgroundThread = new Thread() {
#Override
public void run() {
// do first step
// finished first step
Message msg = Message.obtain();
msg.what = STEP_ONE_COMPLETE;
handler.sendMessage(msg);
}
}
backgroundThread.start();
}
private doBackgroundUpdate2(){
Thread backgroundThread = new Thread() {
#Override
public void run() {
// do second step
// finished second step
Message msg = Message.obtain();
msg.what = STEP_TWO_COMPLETE;
handler.sendMessage(msg);
}
}
backgroundThread.start();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch(msg.what){
case STEP_ONE_COMPLETE:
doBackgroundUpdate2();
break;
case STEP_TWO_COMPLETE:
// do final steps;
break;
}
}
}
You would kick it off by calling doBackgroundUpdate1(), when this is complete it sends a message to the handler which kicks off doBackgroundUpdate2() etc.
Tiger ,
TiGer wrote:
When it's done that same Thread will
return the time-intensive task result
to another (3rd) class
Since thread runs asynchronously so your non-thread class can't be synced with your thread
Though to perform some action on an Activity you need an AsyncTask not A Thread
TiGer wrote:
maybe because this is some kind of
loop ?
Tiger do read more about Threads and concurrency
So the only answer I have for you now is ASYNCTASK
EDIT:
Also I'd like the Thread-class to stop
itself
Read this post's how-do-you-kill-a-thread-in-java
In ordinary Java, you would do this:
class MyTask implements Runnable {
void run() {
for (int i = 0; i < Integer.MAX; i++) {
if (i = Integer.MAX -1) {
System.out.println("done");
}
}
}
}
class MyMain {
public static void main(String[] argv) {
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new MyTask());
t.start();
}
System.out.println("bye");
}
}
... that kicks off 10 threads. Notice that if you accidentally invoke t.run() instead of t.start(), your runnable executes in the main thread. Probably you'll see 'bye' printed before 10 'done'. Notice that the threads 'stop' when the the run() method of the Runnable you gave to them finishes.
I hope that helps you get your head around what it is you've got to co-ordinate.
The tricky part with concurrency is getting threads to communicate with each other or share access to objects.
I believe Android provides some mechanism for this in the form of the Handler which is described in the developer guide under designing for responsiveness.
An excellent book on the subject of concurrency in Java is Java Concurency in Practice.
if you want use AsyncTask rather then thread in android
I have resolve it using ASyncTask and Handler in Android the aim is that one task is execute after compilation of one task hear is code that show First load animation on view after compilation of that process it will goes on another page
class gotoparent extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Animation animation= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotete);
lin2.startAnimation(animation);
}
});
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(getApplicationContext(),ParentsCornor.class);
startActivity(i);
}
}, 1200);
}
}

Categories

Resources