无法调用AsyncTask doInBackground()和onPostExecute

时间:2012-08-14 00:27:09

标签: android android-asynctask

Strangley,我的AsyncTask将执行onPreExecute但不会doInBackground()onPostExecute()。 Logcat没有错误或消息表明出现了问题。

class LocationTask extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.d(TAG, "onPreExecute============");
    }

    @Override
    protected String doInBackground(String... urls) {
        Log.d(TAG, "doInBackground============");
        Log.d(TAG, "urls[0]:" + urls[0]);
        return "test";
    }

    @Override
    protected void onPostExecute(String result){
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.d(TAG, "onPostExecute============");
    }
}

public class CsLocationTaskTest extends AndroidTestCase {

    public void testExecute(){
        LocationTask task = new LocationTask();
        task.execute("my_test_url", null);
    }
}

如您所见,AsycTask并不特别,但doInBackgroundonPostExecute未在测试用例和Activity中都被调用。我不明白发生了什么,请让我明白什么是错的。感谢。

1 个答案:

答案 0 :(得分:0)

AsyncTask必须是CsLocationTaskTest的子类。此外,您不需要null

根据开发文档:

"AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)"

发现于:http://developer.android.com/reference/android/os/AsyncTask.html

试试这个:

 public class CsLocationTaskTest extends AndroidTestCase {

    public void testExecute(){
        LocationTask task = new LocationTask();
        task.execute("my_test_url");
    }

    class LocationTask extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.d(TAG, "onPreExecute============");
    }

    @Override
    protected String doInBackground(String... urls) {
        Log.d(TAG, "doInBackground============");
        Log.d(TAG, "urls[0]:" + urls[0]);
        return "test";
    }

    @Override
    protected void onPostExecute(String result){
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.d(TAG, "onPostExecute============");
    }
}


}