Saturday, May 28, 2016

Android example of using Thread and Handler


This example show how to run code in background using Thread, and also show passing data from activity to thread by calling method of thread, and passing data from thread to activity with Handler.


MainActivity.java
package com.blogspot.android_er.androidthread;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button btnStart, btnStop, btnSend;
    EditText editTextMsgToSend;
    TextView textViewCntReceived, textViewMsgReceived;

    MyThread myThread;
    MyHandler myHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = (Button)findViewById(R.id.startthread);
        btnStop = (Button)findViewById(R.id.stopthread);
        btnSend = (Button)findViewById(R.id.send);
        editTextMsgToSend = (EditText)findViewById(R.id.msgtosend);
        textViewCntReceived = (TextView)findViewById(R.id.cntreceived);
        textViewMsgReceived = (TextView)findViewById(R.id.msgreceived);

        myHandler = new MyHandler(this);

        btnStart.setOnClickListener(btnStartOnClickListener);
        btnStop.setOnClickListener(btnStopOnClickListener);
        btnSend.setOnClickListener(btnSendOnClickListener);
    }

    View.OnClickListener btnStartOnClickListener =
            new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(myThread != null){
                myThread.setRunning(false);
            }
            myThread = new MyThread(myHandler);
            myThread.start();
        }
    };

    View.OnClickListener btnStopOnClickListener =
            new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(myThread != null){
                myThread.setRunning(false);
                myThread = null;
            }
        }
    };

    View.OnClickListener btnSendOnClickListener =
            new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(myThread != null){
                myThread.msgToThread(editTextMsgToSend.getText().toString());
            }
        }
    };

    private void updateCnt(int cnt){
        textViewCntReceived.setText(String.valueOf(cnt));
    }

    private void updateMsg(String msg){
        textViewMsgReceived.setText(msg);
    }


    public static class MyHandler extends Handler{

        public static final int UPDATE_CNT = 0;
        public static final int UPDATE_MSG = 1;
        private MainActivity parent;

        public MyHandler(MainActivity parent) {
            super();
            this.parent = parent;
        }

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what){
                case UPDATE_CNT:
                    int c = (int)msg.obj;
                    parent.updateCnt(c);
                    break;
                case UPDATE_MSG:
                    String m = (String)msg.obj;
                    parent.updateMsg(m);
                    break;
                default:
                    super.handleMessage(msg);
            }

        }
    }
}


MyThread.java
package com.blogspot.android_er.androidthread;

import android.os.Looper;
import android.os.Message;

public class MyThread extends Thread{

    private int cnt;
    private boolean running;
    MainActivity.MyHandler mainHandler;

    public MyThread(MainActivity.MyHandler mainHandler) {
        super();
        this.mainHandler = mainHandler;
    }

    public void setRunning(boolean running){
        this.running = running;
    }

    public void msgToThread(String msgin){
        String msgout = new StringBuilder(msgin).reverse().toString();
        mainHandler.sendMessage(
                Message.obtain(mainHandler,
                        MainActivity.MyHandler.UPDATE_MSG, msgout));
    }

    @Override
    public void run() {
        cnt = 0;
        running = true;

        String prompt;
        if(Looper.myLooper() == Looper.getMainLooper()){
            prompt = "myThread run in UI Thread";
        }else{
            prompt = "myThread run in NOT UI Thread";
        }
        mainHandler.sendMessage(
                Message.obtain(mainHandler,
                        MainActivity.MyHandler.UPDATE_MSG, prompt));

        while (running){
            try {
                Thread.sleep(1000);
                mainHandler.sendMessage(
                        Message.obtain(mainHandler,
                                MainActivity.MyHandler.UPDATE_CNT, cnt));

                cnt++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    tools:context="com.blogspot.android_er.androidthread.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <Button
        android:id="@+id/startthread"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Thread"/>
    <Button
        android:id="@+id/stopthread"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Thread"/>
    <EditText
        android:id="@+id/msgtosend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="msg to send..." />
    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send msg to thread"/>
    <TextView
        android:id="@+id/cntreceived"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="26dp"/>
    <TextView
        android:id="@+id/msgreceived"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textStyle="bold"
        android:textSize="20dp"/>
</LinearLayout>



download filesDownload the files .

Related:
Android example of using Service and BroadcastReceiver
Example of IntentService and BroadcastReceiver

No comments: