0

I have the below singleton handler class

public class MyHandler
{
private static Handler handler;
private static boolean isRunning;

public static Handler getHandler(Runnable myRunnable)
{
    if (handler == null)
    {
        initHandler(myRunnable);
    }
    return handler;
}


private static void initHandler(Runnable myRunnable)
{
    handler = new Handler();
    isRunning = true;
    handler.postDelayed(myRunnable, 5000);
}

public static void reRunHandler(Runnable myRunnable)
{
    isRunning = true;
    handler.postDelayed(myRunnable, 45000);
}

public static void stopMyHandler()
{
    isRunning = false;
    handler.removeCallbacksAndMessages(null);
}
}

However, how can I update my UI from here ? As the runnables are inside my activity. Apparently I cannot use getHandleMessage to communicate with it.

If you need more code, how am I using this, I can share.

tony9099
  • 4,567
  • 9
  • 44
  • 73

2 Answers2

1

It's very simple:

new Handler(Looper.getMainLooper()).post(new Runnable() {           
    @Override
    public void run() {
        //do whatever you want on the UI thread
    }
});
0

Handle has functions for this purposes:

private final Handler handler =  new Handler() {
    public void handleMessage(Message msg) {

        // here you can get data from Message and update your UI. runs in UI thread

    }
};

If you will send message with data to your Handler use next code:

Message m = new Message();
Bundle b = new Bundle();
b.putInt("myNumber", 5); // for example
m.setData(b);
myHandler.sendMessage(m);
Veaceslav Gaidarji
  • 4,261
  • 3
  • 38
  • 61
  • true, however, this is a singleton class (as you can see), which runs inside a runnable on a separate thread than the UI. Where/How should I implement that ? – tony9099 Sep 23 '13 at 15:22
  • Implement handleMessage method where you defining your Handler field – Veaceslav Gaidarji Sep 23 '13 at 15:25
  • Okay, however I do not think I can do network activity in there. – tony9099 Sep 23 '13 at 19:31
  • 1
    will you do network activity there or will you update UI? choose please :) – Veaceslav Gaidarji Sep 23 '13 at 20:18
  • how can I do network activity there ? It is running on the UI thread, the network calls will throw exceptions. I tried it. – tony9099 Sep 24 '13 at 14:53
  • oh, sorry man. yes, you cannot do network activity inside handleMessage method. Look, you can make your network activity in background thread and communicate with you handler like: MyHandler.getHandler(...).sendMessage(m). in handleMessage() method you can update your UI. Try this mechanism, it should work. – Veaceslav Gaidarji Sep 24 '13 at 18:14
  • I'm afraid it does not, because we are using a singleton class and not dealing directly with the handler, so the handler is actually in another class. I think the key for this is to use runOnUiThread(myRunnable); or similar.. i will look more into it – tony9099 Sep 25 '13 at 09:33