假设您正在使用 AsyncTask,您可以在活动 B 中创建一个回调,您可以在 AsyncTask 的 onPostExecute 中调用该回调,将下载的数据传递给活动 B。这样,您只需在活动 B onCreate 中放置一个加载对话框,并注意在回调中加载数据。
A:
public class ActivityA extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
//start download task
ActivityB b = new ActivityB();
startActivity(new Intent(getApplicationContext(), b.getClass()));
new Task(b.new DownloadCallback()).execute();
}
}
乙:
public class ActivityB extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
//show a progress dialog
return super.onCreateView(name, context, attrs);
}
private void loadData(/*Your data*/){
//Load your data
System.out.println("data loaded");
}
public class DownloadCallback {
public void onFinish(/*Your data*/) {
loadData(/*Your data*/);
}
}
}
任务:
public class Task extends AsyncTask<Void, Void, Object>{//Change the Object to whatever your data is
private DownloadCallback callback;
public Task(DownloadCallback callback) {
this.callback = callback;
}
@Override
protected Object doInBackground(Void... params) {
//Download data here
//Change the Object return value to whatever your data is
return true;
}
@Override
protected void onPostExecute(Object result) {
//Change the Object to whatever your data is and pass to the finish method
callback.onFinish(/*Your data*/);
}
}