Home  >  Android

Android Handler, DialogFragment and Time Picker Example with Message and Bundle

By Arvind Rai, June 10, 2015
This page will walk through Android Handler, DialogFragment and Time Picker Example with Message and Bundle. Handler is used to send and receive Message. DialogFragment creates fragment controlled by API that will prompt on top of activity window like alert box, date picker and time picker. We will create here a time picker dialog using TimePicker and TimePickerDialog. Bundle carries the data with Message. It provides put and get method for data. In our time picker dialog, after selecting time, it will be displayed on activity window with a text view.


android.os.Handler is used to send and process Message associated with a thread's message queue. The new instance of Handler is associated to the thread which has created it and its message queue. Handler is used to schedule messages at any future point and it enqueues action to be performed on any different threads. In case of creating any Dialog, we can send the message to it and can get return the messages sent by Dialog with the help of Handler. Find some methods of Handler.

handleMessage(Message msg): Receives the messages. The subclass must implement this method.
dispatchMessage(Message msg) : Used for system message.
obtainMessage() : Returns Message.
post(Runnable r) : Adds Runnable instance to message queue.
sendMessage(Message msg) : Pushes the message at the end of message queue.

In our example we are creating a time picker dialog. Using Handler we pass the current time to time picker dialog and get return the set time by dialog. To achieve it, we do code as below. Create the instance of Handler overriding the handleMessage(). Create a class extending Handler and override its handleMessage().
class MyHandler extends Handler {
    public void handleMessage (Message msg){
    	Bundle bundle = msg.getData();
    	timeHour = bundle.getInt(MyConstants.HOUR);
    	timeMinute = bundle.getInt(MyConstants.MINUTE);
    	textView.setText(timeHour + ":" + timeMinute);
By Message instance we get Bundle instance and can get all the information added to it. To send message back by any Dialog, we use
Message msg = new Message();
We will see the full example in our post for Handler .


android.support.v4.app.DialogFragment is a fragment which opens a dialog on top of activity window. The control of dialog is done by API. To use it we have to write a class extending DialogFragment and override a method onCreateDialog(Bundle). In this way, we create an entirely custom dialog. Dialogs are often autonomous window which decides its input and disappear by its own time receiving any button click etc. Find some methods of it.

onCreate (Bundle savedInstanceState) : It takes part in initial creation of fragment.
onCreateDialog(Bundle savedInstanceState) : It returns Dialog and helps to create custom dialog.
onDestroyView() : It is called when dialog is removed.
onStart() : It is called when dialog is viewable to user.
onStop() : It is called when fragment is stopping.

In our example we are creating time picker dialog using DialogFragment.

TimePicker and TimePickerDialog

android.widget.TimePicker is a view in which we can select hour and minute of the day using 24 hour view or 12 hour view with AM and PM. We can select hour and minute using vertical spinner. We can also enter data using keyboard. android.app.TimePickerDialog is displays a dialog for TimePicker. TimePickerDialog has two public constructors. We create the instance of it by passing context, hour, minute and Boolean value for 24 hour view.


android.os.Message is used to define message that is sent to Handler. Find some method details.

setData(Bundle data) : Sets a bundle.
getData(): Returns a bundle.
getTarget() : Returns the target handler that will receive message.
copyFrom(Message ob) : Copy the calling message into the argument message i.e ob.


android.os.Bundle extends android.os.BaseBundle and is used to map String values to Parcelable types. We put the values as int, String etc. It provides methods like putInt(), putChar() etc and to fetch values it has methods like getInt(), getChar() etc.

Complete Example

Now find the complete example. Here we will create a time picker dialog using which we can select time. The selected time will be displayed using text view.

Software Used in Example

In our example we are using software and tools as follows.
1. Java 7
2. Android 4.4W
3. Eclipse

FragmentActivity and DialogFragment Implementation

package com.concretepage.android;
import java.util.Calendar;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.concretepage.R;
public class MainActivity extends FragmentActivity{
	private static int timeHour = Calendar.getInstance().get(Calendar.HOUR);
	private static int timeMinute = Calendar.getInstance().get(Calendar.MINUTE);
	TextView textView;
        public void onCreate(Bundle savedInstanceState) {
		textView = (TextView)findViewById(R.id.msg);
		textView.setText(timeHour + ":" + timeMinute);
                OnClickListener listener = new OnClickListener() {
			public void onClick(View view) {
				Bundle bundle = new Bundle();
				bundle.putInt(MyConstants.HOUR, timeHour);
				bundle.putInt(MyConstants.MINUTE, timeMinute);
				MyDialogFragment fragment = new MyDialogFragment(new MyHandler());
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                transaction.add(fragment, MyConstants.TIME_PICKER);
               Button btn = (Button)findViewById(R.id.button);
        class MyHandler extends Handler {
    	       public void handleMessage (Message msg){
    		   Bundle bundle = msg.getData();
    		   timeHour = bundle.getInt(MyConstants.HOUR);
    		   timeMinute = bundle.getInt(MyConstants.MINUTE);
    		   textView.setText(timeHour + ":" + timeMinute);

package com.concretepage.android;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.widget.TimePicker;
public class MyDialogFragment extends DialogFragment {
	private int timeHour;
	private int timeMinute;
	private Handler handler;
	public MyDialogFragment(Handler handler){
		this.handler = handler;
	public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        timeHour = bundle.getInt(MyConstants.HOUR);
        timeMinute = bundle.getInt(MyConstants.MINUTE);
		TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				timeHour = hourOfDay;
				timeMinute = minute;
				Bundle b = new Bundle();
				b.putInt(MyConstants.HOUR, timeHour);
				b.putInt(MyConstants.MINUTE, timeMinute);
				Message msg = new Message();
	        return new TimePickerDialog(getActivity(), listener, timeHour, timeMinute, false);

package com.concretepage.android;
public abstract class MyConstants {
	public static final String HOUR = "time_hour";
	public static final String MINUTE = "time_minute";
	public static final String TIME_PICKER = "time_picker";


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11" />
        android:allowBackup ="false"
        android:label="@string/app_name" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

Layout XML

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


<?xml version="1.0" encoding="utf-8"?>
    <string name="app_name">Concrete Page</string>
    <string name="btn_label"> Change Time </string>


Find the output.
Android  Handler, DialogFragment  and Time Picker Example with Message and Bundle

Download Source Code


©2022 concretepage.com | Privacy Policy | Contact Us