Multi-Threading in Android Using Handler for message queue

Forums » Android - Examples > Multi-Threading in Android Using Handler for message...
October 13, 2011 2:22:36 AM PDT (one year ago). Seen 19,131 times. 2 replies.
Photo Vaibhav Parkhi
None
Member since Sep 19, 2011
Forum Posts: 3
Android have following Threads state:

Advantages of Multi-Threading
1.Threads share the process' resources but are able to execute independently.
2.Applications responsibilities can be separated main thread runs UI, and slow tasks are sent to background threads.
3.Threading provides an useful abstraction of concurrent execution.
4.Particularly useful in the case of a single process that spawns multiple threads on top of a multiprocessor system. In this case real parallelism is achieved.
5.Consequently, a multithreaded program operates faster on computer systems that have multiple CPU's.


Handler Class
http://developer.android.com/reference/android/os/Handler.html
•When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, intent receivers, etc) and any windows they create.
•You can create your own secondary threads, and communicate back with the main application thread through a Handler.
•When you create a new Handler, it is bound to the message queue of the thread that is creating it --from that point on, it will deliver messagesand runnablesto that message queue and execute them as they come out of the message queue.

Code for Multi-threading using Handler class

Code:
package com.android.multithreading;

import java.util.Random;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.inputmethodservice.Keyboard.Key;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ThreadingActivity extends Activity implements Runnable

{
/*
* ThreadingActivity class for managing multi-tasking using message queue
*/
/** Called when the activity is first created. */
ProgressBar pb1;
ProgressBar pb2;
TextView msgWorking;
TextView msgReturned;
TextView pdTv;
Button pdBtn;
private String pi_string;
ProgressDialog pd;
boolean isRunning=false;
final int MAX_SEC=60;
String strTest="Global value seen by all threads";
int intTest=0;

Handler handler=new Handler()
{
@Override
public void handleMessage(Message msg)
{
String returnValue=(String)msg.obj;
Log.i(returnValue, " Return Value");
msgReturned.setText("returned by background thread: \n\n"+returnValue);
pb1.incrementProgressBy(2);

if(pb1.getProgress()==MAX_SEC)
{
msgReturned.setText("Done \n back thread has been stopped");
isRunning=false;
}
if(pb1.getProgress()==pb1.getMax())
{
msgWorking.setText("Done");
pb1.setVisibility(View.INVISIBLE);
pb2.setVisibility(View.INVISIBLE);
pb1.getLayoutParams().height=0;
pb2.getLayoutParams().height=0;
}
else
{
msgWorking.setText("Working..."+pb1.getProgress()+"%");

}
}
};// handler
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pb1=(ProgressBar)findViewById(R.id.progress);
pb2=(ProgressBar)findViewById(R.id.progress2);
pb1.setMax(MAX_SEC);
pb1.setProgress(0);
msgWorking=(TextView)findViewById(R.id.TextView01);
msgReturned=(TextView)findViewById(R.id.TextView02);
pdTv=(TextView)findViewById(R.id.TextView03);
pdBtn=(Button)findViewById(R.id.pdBtn);
pdBtn.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
//Intent i=new //Intent(getApplicationContext(),ThreadsPosting.class);
//startActivity(i);
}
});
strTest+="-01";
intTest=1;
}
public void onStop()
{
super.onStop();
isRunning=false;
}

public void onStart()
{
super.onStart();
Thread background=new Thread(new Runnable() {

public void run()
{
// TODO Auto-generated method stub
try
{
for(int i=0;i<MAX_SEC && isRunning;i++)
{
Thread.sleep(1000);

Random rnd=new Random();
String data="Threads Value "+(int)rnd.nextInt(101);
data+="\n"+strTest+" "+intTest;
intTest++;

Message msg=handler.obtainMessage(1, (String)data);

if(isRunning)
{
handler.sendMessage(msg);
}

}
}
catch(Throwable e)
{

}

}//run
});// background
isRunning=true;
background.start();

}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub

pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,false);
Thread th=new Thread(this);
th.start();
return super.onKeyDown(keyCode, event);
}

public void run() {
// TODO Auto-generated method stub
Random rnd=new Random();
pi_string = Pi.computePi(800).toString();
handler2.sendEmptyMessage(0);

}

private Handler handler2=new Handler()
{
@Override
public void handleMessage(Message msg)
{
pd.dismiss();
pdTv.setText(pi_string);
}
};




}




February 3, 2013 11:06:53 PM PST (14 weeks ago)
Photo Android Example
Android Example
Flexsoftech.com
Member since Feb 3, 2013
Forum Posts: 1
Nice Thread Tutorial, i am new in android , its help me a lot ...

http://androidexample.com/Thread_With_Handlers_-

_Android_Example/index.php?view=article_discription&aid=58&aaid=83
Edited one time. Last edit by Android Example on Feb 3, 2013 at 11:08:28 PM (about one year ago).
March 17, 2013 7:58:02 PM PDT (8 weeks ago)
Photo Neha Somany
student
PICT
Member since Mar 17, 2013
Forum Posts: 1
Hi, I have a query. Can we send same Message object with updated values of Bundle using same handler?

Because, I am trying to interprete co-ordinate values using working thread and then thread send message using handler to UI thread, where I am supposed to draw lines.

for example, can I have a code like this:

Code:
class TestView extends View {

//Paint p;
float x1;
float y1;
float x2;
float y2;
Bitmap bitmap=Bitmap.createBitmap(1000, 1000, Config.ARGB_8888);
Canvas canvas=new Canvas(bitmap);
Paint p=new Paint();


Handler handler=new Handler(){

@Override
public void handleMessage(Message msg) {

p.setColor(Color.BLUE);
Bundle bundle=msg.getData();
x1=bundle.getFloat("x1");
y1=bundle.getFloat("y1");
x2=bundle.getFloat("x2");
y2=bundle.getFloat("y2");

Toast.makeText(getContext(), "value x1: "+ x1, Toast.LENGTH_LONG).show();



}

};

public TestView(Context context) {
super(context);
Paint p=new Paint();
p.setColor(Color.BLUE);
new Thread(){
public void run(){
Looper.prepare();
Message msg=new Message();
Bundle bundle=new Bundle();
Bundle bundle1=new Bundle();

bundle.putFloat("x1", 10);
bundle.putFloat("y1", 10);
bundle.putFloat("x2", 100);
bundle.putFloat("y2", 100);
msg.setData(bundle);
handler.sendMessage(msg);

bundle1.putFloat("x1", 100);
bundle1.putFloat("y1", 100);
bundle1.putFloat("x2", 150);
bundle1.putFloat("y2", 150);
msg.setData(bundle1);
handler.sendMessage(msg);
Looper.loop();



}
}.start();


}



boolean isDrawing=true;

@Override
protected void onDraw(Canvas canvas) {
//canvas.drawLine(x1, y1, x2, y2, p);

}





}


What I have seen is, it doesn't display any toast in this case; but if I set the Message object name different, then it works. But if is it so, functionality of program will break, as I have to switch commands, then calculate cordinates and then send message to handler to update canvas contents. Please give me solution.

Thank you!
Edited one time. Last edit by Neha Somany on Mar 17, 2013 at 7:59:46 PM (about one year ago).