只需将AsyncTask创建为Activity的内部类,或将Context传递给AsyncTask的构造函数.

内部类:MyActivity.java

public class MyActivity extends Activity {

// your other methods of the activity here...

private class MyTask extends AsyncTask {

protected Void doInBackground(Void... param) {

publishProgress(...); // this will call onProgressUpdate();

}

protected Void onProgressUpdate(Void... prog) {

Toast.makeText(getActivity(), "text", 1000).show();

}

}

}

构造函数:MyTask.java

public class MyTask extends AsyncTask {

Context c;

public MyTask(Context c) {

this.c = c;

}

protected Void doInBackground(Void... param) {

publishProgress(...); // this will call onProgressUpdate();

}

protected Void onProgressUpdate(Void... prog) {

Toast.makeText(c, "text", 1000).show();

}

}

此外,请不要忘记在对话框上调用.show().

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

builder.show();

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐