我建议实现一个处理程序回调。您可以将片段(或活动)的处理程序传递给 AsyncTask,AsyncTask 将在完成时调用它。AsyncTask 也可以传回任意对象。
这是一个示例 AsyncTask,我在它自己的文件中(不是子类):
public class MyTask extends AsyncTask<Void, String, String> {
private static final String TAG = "MyTask";
private Handler mCallersHandler;
private Candy mObject1;
private Popsicle mObject2;
// Return codes
public static final int MSG_FINISHED = 1001;
public SaveVideoTask(Handler handler, Candy candyCane, Popsicle grapePop ) {
this.mCallersHandler = handler;
this.mObject1 = candyCane;
this.mObject2 = grapePop;
}
@Override
protected String doInBackground(Void... params) {
// Do all of the processing that you want to do...
// You already have the private fields because of the constructor
// so you can use mObject1 and mObject2
Dessert objectToReturn = mObject1 + mObject2;
// Tell the handler (usually from the calling thread) that we are finished,
// returning an object with the message
mCallersHandler.sendMessage( Message.obtain( mCallersHandler, MSG_FINISHED, objectToReturn ) );
return (null);
}
}
此示例假定您的 AsyncTask 需要一块糖果和一根冰棒。然后它将向您的片段返回一个甜点。
您可以使用以下代码在片段中的一行中构造和运行 AsyncTask:
( new MyTask( mFragmentHandler, candyCane, grapePop ) ).execute();
但当然,您首先需要设置片段的处理程序 (myFragmentHandler)。为此,您的片段(或活动)应如下所示(注意“实现 Handler.Callback”):
public class MyFragment extends Fragment implements Handler.Callback {
private Handler mFragmentHandler;
private Candy candyCane;
private Popsicle grapePop;
@Override
public void onCreate(Bundle savedInstanceState) {
// Standard creation code
super.onCreate(savedInstanceState);
setRetainInstance(true);
// Create a handler for this fragment
mFragmentHandler = new Handler(this);
// Other stuff...
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
// Inflate the layout
View v = inflater.inflate(R.layout.my_fragment_layout, parent, false );
// The candyCane and grapePop don't need to be set up here, but
// they MUST be set up before the button is pressed.
// Here would be a good place to at least initialize them...
// Perhaps you have a button in "my_fragment_layout" that triggers the AsyncTask...
Button mButton = (Button) v.findViewById(R.id.mButton);
mButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
( new MyTask( mFragmentHandler, candyCane, grapePop ) ).execute();
}
});
return v;
}
@SuppressWarnings("unchecked")
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MyTask.MSG_FINISHED:
// Let's see what we are having for dessert
Dessert myDessert = (Dessert) msg.obj;
break;
}
return false;
}
}
如果您使用这些代码,按下按钮将触发 AsyncTask。调用片段将在 AsyncTask 处理期间继续执行。然后,当 AsyncTask 完成时,它会向 Fragment 发送一条消息,表示它已完成,并随消息传递一个对象。此时,fragment 将看到消息,并为所欲为。
注意:可能有错别字。这是从一个非常大而复杂的代码中剪下来的。