Skip to main content

Threads and Handlers

Newbies in Android face difficulty with communicating between different threads.

It is better to create a new background thread instead of delaying the UI thread when there is lengthy task.
Let us say you want to read an html file. If you read this file in UI thread, the program appears to be unresponsive. Hence it is better to read the file in a background thread.
But when this reading is completed, how do you show the html in a webview in this example? The background threads can not access the ui widgets. Hence there is a need to communicate between ui thread and background thread.
This can be done with Handlers. Handlers are used to send and process messages. A handler created in  a thread, can process all the messages sent by this thread.



You should create a handler class for processing messages


private class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {  
 
if(msg.getData().getString("message").equals("your message here")){
Toast.makeText(ShowPage.this, "your toast here...", Toast.LENGTH_LONG).show();
}
}
    
    }

Next  initialize an object of this MyHandler class in onCreate

class MyActivity extends Activity
{
    MyHandler mHandler;
//more variables here
//


public void onCreate(Bundle b){
            //some code here
            mHandler = new MyHandler();
            //
}


Let us say I create a thread to write to a file

Thread th = new Thread(){
        public void run(){
            //here goes my lengthy
            //processing statements
            ------


           //processing completed
           Message msg = new Message();
           Bundle b = new Bundle();
                           b.putString("message", "your message here");//key and value
           msg.setData(b); 
                           mHandler.sendMessage(msg);//inform that thread is completed
}
}//my thread ends here


At the end, I should create a message object and write the string to it. Then send this message to the handler.
Handler has handleMessage method which checks at the string and if it is matching, takes appropriate action.

That's all.  Our thread with handler is ready to go.




Comments

Popular posts from this blog

Copy to clipboard

In my upcoming app, I have codes which I display. These are some times lengthy, and I want the app to be able to copy this to clipboard. Once it is in clipboard, users can paste it anywhere. So how do you copy some text from your app to clipboard. You need to use clipboard manager. Clipboard Manager This class sets and gets data for the clipboard using Clipdata objects.  You can get the object of this class using system service.  - using statement context.getSystemService(Context.CLIPBOARD_SERVICE) Example I have a dummy project with a button, onclick of which copies content to clipboard. Here is my activity file package com . hegdeapps . testapp ; import android.content.ClipData ; import android.content.ClipboardManager ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; import android.view.View ; import android.widget.Button ; import android.widget.TextView ; public class MainActivity extends ...

Drawables in Android - Layer drawable

Let us see how to use layer drawable. You can have two or more bitmaps on different layers to create such a drawable Using xml : You should use layer-list in your xml file to create layerdrawable. Here is layer.xml <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <bitmap android:src="@drawable/whiteicon" android:gravity="top|left"/> </item> <item> <bitmap android:src="@drawable/blueicon" android:gravity="top|left"/> </item> <item> <bitmap android:src="@drawable/redicon" android:gravity="top|left"/> </item> </layer-list> We are using three different bitmaps whiteicon.png, redicon.png and blueicon.png which are present in /res/drawable/mdpi folder. All these are of different sizes and aligned to top left. Thi...

Using a list fragment with cursor adapter

All these days, I avoided using fragments. But then I realized for my this particular applications fragments are ideal. I have a master - detail list in my app. Let us say you want to have two fragments - one is a fragment which contains a list of elements and second one expands one element of the list. Both of them share the same cursor from the activity. Let us start with list fragment. Do not try creating list fragment using a wizard. It unnecearrily adds too many methods and classes. Let us start writing our own fragment like this class MyListFragment extends ListFragment { } Next using code menu override option, override the following method onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) This method should be used for inflating the layout file for the fragment.  I have a framelayout in parent activity of this fragment with the id as container. So I will specify that for inflating. The framelayout will be the paren...