从单一实例处理程序类更改 UI



>我有以下单例处理程序类

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

但是,如何从此处更新我的 UI?因为可运行对象在我的活动中。显然我无法使用getHandleMessage与它进行通信。

如果你需要更多的代码,我如何使用这个,我可以分享。

这很简单:

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

句柄具有用于此目的的函数:

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

相关内容

  • 没有找到相关文章

最新更新