Thread and Handler

The graphic interface cannot be modified by another thread, so when you use a different thread to make calculations or another task and you want to show the result in the activity, you will need a handler.

import android.os.Handler; import android.os.Message; import java.lang.ref.WeakReference; public class TimeHandler extends Handler { private final WeakReference<MainActivity> mainActivityWeakReference;
public TimeHandler(MainActivity mainActivity){ mainActivityWeakReference= new WeakReference<MainActivity>(mainActivity); } @Override
 public void handleMessage(Message ms){
MainActivity activity=mainActivityWeakReference.get(); if (activity!=null){ activity.showElapsedTime();//this is the function in your activity which updates. } } }

you need to declare a handler variable
public static TimeHandler handler;
and initiate it inside the activity which receives the messages.
Val.handler=new TimeHandler(this);
In this case I have declared handler as static inside a class named Val. 
(I store here some values)
Then, when your processing thread needs to change the call it from a thread
public class TimeThread extends Thread { public boolean running; public void TimeTread(){ } public void run(){ Log.i("main","thread begins"); while (running){ try { sleep(200); Val.handler.sendEmptyMessage(0); } catch (Exception e){} } Log.i("main","thread ends"); } }

here I use an empty message
you can send a more complex message via the Message class

        Val.handler.sendMessage(m);

to make the message see this.




To use the thread:
declare it
TimeThread myThread;

Initialize it and start runnig
myThread=new TimeThread(); myThread.running = true; myThread.start();
"running" is a boolean variable to loop the activity of the thread.

And when the task is completed, stop the thread:
if (myThread.isAlive()){ boolean repeat=false; myThread.running=false; while (repeat){ try { myThread.join(); repeat=false; } catch (Exception e){} } }




No comments:

Post a Comment