2

我有一个计时器,我想在倒计时完成后启动 AsyncTask。如果我将它的执行放在一个处理程序中,它会循环它并多次启动它。如果我不把它放在处理程序中,我会遇到以下崩溃: 无法在未调用 looper.prepare() 的线程内创建处理程序

timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));

class ListUpdate extends TimerTask {
    private Handler mHandler = new Handler(Looper.getMainLooper());
    public void run() {
        mHandler.post(new Runnable() {
            public void run() {
                AsyncTask<Integer, Void, Boolean> task = new updateList();
                task.execute();
            }
        });
    }
}

关于如何解决这个问题的任何建议?

4

2 回答 2

5

AsyncTask应该只在 UI 线程上运行。在您的情况下,您似乎没有在 UI 线程上正确运行它。

也许试试这样:

timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));

class ListUpdate extends TimerTask {
    Looper looper = Looper.getMainLooper();
    looper.prepareMainLooper();

    private Handler mHandler = new Handler(looper);
    public void run() {
        mHandler.post(new Runnable() {
            public void run() {
                AsyncTask<Integer, Void, Boolean> task = new updateList();
                task.execute();
            }
        });
    }
}
于 2012-05-08T10:22:56.820 回答
0

通过在我从 TimerTask 调用的 TimerTask 之外添加一个处理程序,我可以使它工作!

final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        RelativeLayout rl_header = (RelativeLayout)findViewById(R.id.rl_header);
        Desktop desktop = helper.getDesktop();
        try {
            desktop.inflate(ll, rl_header, banners, DesktopApp.this);
            Collections.sort(helper.nextListUpdate);
            helper.nextListUpdate.remove(0);
            timer = new Timer();
            if (helper.nextListUpdate.size() > 0) timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
     }

};

class ListUpdate extends TimerTask {
    public void run() {
        DesktopApp.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        });
    }
}
于 2012-05-09T07:40:39.447 回答