AsyncTask中的Android Looper.prepare()

时间:2015-01-05 07:28:22

标签: android android-asynctask

在我的应用程序中,我试图通过AsyncTask从webservice中检索数据。在这段代码中我将长操作放入AsyncTask但是我得到了这个错误:

FATAL EXCEPTION: Thread-10
java.lang.ExceptionInInitializerError at
icq.ms.Activities.ActivitySendArchive$4.run(ActivitySendArchive.java:298)
01-05 10:52:30.905: E/AndroidRuntime(467): 
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

我的代码:

Thread request_thread = new Thread() {
    @Override
    public void run() {
        new LongOperationList().execute ("");
    }
};
request_thread.start ();

LongOperationList代码块:

private class LongOperationList extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        G.db.deleteArchive ( G.config_username );
        try {
            getRequestFromServer ( 0, 10 );
        } catch (Exception e) {
            if( G.DEBUG ) G.DebugLog.log( e + "" );
        }
        return "";
    }

    @Override
    protected void onPostExecute(String result) {
        progress_bar.setVisibility ( View.GONE );
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

如何将Looper.prepare()调用到AsyncTask?

2 个答案:

答案 0 :(得分:0)

您必须像以下一样调用AsyncTask:

new LongOperationList().execute ("");

答案 1 :(得分:0)

不需要从线程启动长操作任务,只需

将此更改为

Thread request_thread = new Thread() {
    @Override
    public void run() {
        new LongOperationList().execute ("");
    }
};
request_thread.start ();

:此

new LongOperationList().execute ("");