Handler Thread Activity In Android Programming

This example will show you how to handle parent and child thread and switch between activities.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it HandlerThreadActivity.

2.) Write following into main.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<Button
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/start_thread"></Button>
</LinearLayout>

 

3.) Run for output.

Steps:

1.) Create a project named HandlerThreadActivity and set the information as stated in the image.

Build Target: Android 4.2
Application Name: HandlerThreadActivity
Package Name: com. HandlerThreadActivity
Activity Name: HandlerThreadActivity
Min SDK Version: 4.2

2.) Open HandlerThreadActivity.java file and write following code there:

 

package com.handlerthreadactivity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class HandlerThreadActivity extends Activity{

private Button start;
private ProgressDialog progressDialog;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.Button01);
start.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
fetchData();
}

});
}

protected void fetchData() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(this, "", "Loading...");
new Thread() {
public void run() {
try {

Thread.sleep(800);

} catch (InterruptedException e) {

}
messageHandler.sendEmptyMessage(0);

}
}.start();
}

private Handler messageHandler = new Handler() {

public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
}
};
}

 

 

4.) Compile and build the project.

Output