从Handler创建的aSyncTask

时间:2012-03-18 00:27:59

标签: android android-asynctask

这是我首先要做的。我正在尝试启动一个MapView,它可以抓取用户的位置并加载一个覆盖层,其中的数据会根据用户的位置而变化。

代码概述: 我有一个MapView,可以在创建时抓取当前用户的位置。 我正在使用的locationOverlay在第一次修复时调用Runnable:

locationOverlay.runOnFirstFix(centerAroundFix);

此Runnable,centerAroundFix,启动aSyncTask。一旦我调用'new aSyncTask',就会抛出此错误:

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

asynctask的工作是获取数据,创建叠加层并添加叠加层。创建和执行asynctask在Runnable之外工作正常。

2 个答案:

答案 0 :(得分:0)

不知道我怎么没看到这个......

Can't create handler inside thread which has not called Looper.prepare()

我很确定这是一个重复的问题。

编辑:有效。这是我的代码。用“mHandler.post”包装updateLocation()调用:

private Handler mHandler = new Handler(Looper.getMainLooper());

private Runnable centerAroundFix = new Runnable() {
    public void run() {
        /* Jump to current location and set zoom accordingly */
        map.getController().animateTo(locationOverlay.getMyLocation());
        map.getController().setZoom(12);
        /* This is a different thread.  I need to call this from a thread that has a 'Looper' prepared. */
        mHandler.post(new Runnable() {
            public void run() {
                updateLocation();
            }
        });
    }
};

答案 1 :(得分:0)

您必须在UIThread中创建Handler。例如,作为类成员:

public class Activity extends Activity{
    private Handler handler = new Handler();        
}