【问题标题】:Cannot call AsyncTask doInBackground() and onPostExecute无法调用 AsyncTask doInBackground() 和 onPostExecute
【发布时间】:2012-08-14 00:27:08
【问题描述】:

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 没有什么特别之处,但是在测试用例和我的Activity 中都没有调用doInBackground 和onPostExecute。我不明白发生了什么,请让我了解发生了什么问题。谢谢。

【问题讨论】:

  • 感谢您的回答。我会更多地搜索并尝试不同的方式。

标签: android android-asynctask


【解决方案1】:

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============");
    }
}


}

【讨论】:

  • 对不起,伙计。您的代码无法按我的意愿工作。它仍然是一样的。 AsyncTask 应该在 Thread 中测试。我使用 InstrumentationTestCase 类和 runTestOnUiThread 方法解决了这个问题。
  • 可能是这样,但你仍然需要继承 AsyncTask 的子类,如果你保持原来的样子,它永远不会起作用。只需确保在使用它来构建应用程序时,您是 AsyncTask 的子类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
相关资源
最近更新 更多