从单例处理程序类更改UI

时间:2013-09-23 15:10:20

标签: android handler runnable ui-thread android-handler

我有以下单例处理程序类

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);
}
}

但是,如何从这里更新我的用户界面?由于runnables在我的活动中。显然我不能使用getHandleMessage与它进行通信。

如果您需要更多代码,我如何使用它,我可以分享。

2 个答案:

答案 0 :(得分:1)

这很简单:

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

答案 1 :(得分:0)

Handle具有用于此目的的功能:

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

    }
};

如果您要向处理程序发送包含数据的消息,请使用下一个代码:

Message m = new Message();
Bundle b = new Bundle();
b.putInt("myNumber", 5); // for example
m.setData(b);
myHandler.sendMessage(m);