无法在未调用 Looper.prepare() 的线程中创建处理程序 Graphhopper



我遇到了以下错误。

logUser("An error happend while creating graph:"+ getErrorMessage());

其中getErrorMessage()是不能在未调用Looper.prepare()的线程中创建处理程序,而logUser是一个只显示toast congaing消息的函数。

void prepareGraph() {
    logUser("loading graph (" + Helper.VERSION + "|" + Helper.VERSION_FILE
            + ") ... ");
    new MyAsyncTask<Void, Void, Path>() {
        protected Path saveDoInBackground(Void... v) throws Exception {
            GraphHopper tmpHopp = new GraphHopper().forAndroid();
            tmpHopp.contractionHierarchies(true);
            tmpHopp.load(mapsFolder + currentArea);
            logUser("found graph with " + tmpHopp.getGraph().nodes() + " nodes");
            hopper = tmpHopp;
            return null;
        }
        protected void onPostExecute(Path o) {
            if (hasError()) {
                logUser("An error happend while creating graph:"
                        + getErrorMessage());
            } else {
                logUser("Finished loading graph. Touch to route.");
                calcPath(52.534185, 13.348732, 52.53857,
                        13.41259);
            }
            finishPrepare();
        }
    }.execute();
}

你不能在后台线程做UI操作。

试试这个:

GraphHopper tmpHopp = new GraphHopper().forAndroid();
tmpHopp.contractionHierarchies(true);
tmpHopp.load(mapsFolder + currentArea);
runOnUiThread(new Runnable() {    
    public void run() {
        logUser("found graph with " + tmpHopp.getGraph().nodes() + " nodes");
    }
});
hopper = tmpHopp;
return null;

您需要在主线程上实例化您的AsyncTaskAsyncTask源代码创建了一个Handler来调用你的onPreExecute(), onPostExecute()等方法,如果Handler没有在主线程上实例化,Android会抛出一个异常,告诉你Handler正在交互的线程没有调用它的Looper.prepare()方法。

最新更新