问题
I have an inner AsyncTask which i have call from a fragment outside the fragment which contains this AsyncTask. I have read and saw some examples where they use an interface. I can't figure it out on how to implement it in my project.
This is my inner AsyncTask:
public class LoadQueueTask extends AsyncTask<Void, Void, Queue>
{
@Override
protected Queue doInBackground(Void... arg0) {
Model model = Model.getInstance();
return model.getQueue();
}
@Override
protected void onPostExecute(Queue result) {
super.onPostExecute(result);
queue = result;
if(result == null) {
listview.setEmptyView(empty);
progress.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
emptyText.setText("Empty Queue");
emptyImage.setImageResource(R.drawable.ic_action_warning);
} else {
if(result.getSlots().size() != 0) {
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
callAsynchronousTask();
}
}, 5000);
} else {
listview.setEmptyView(empty);
progress.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
emptyText.setText("No items found");
}
}
}
}
Here is my fragment where i want to execute this task:
public class Fragment extends SherlockFragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment, container, false);
}
ViewPager mViewPager = (ViewPager) rootView.findViewById(R.id.viewPager);
kbps = (TextView) rootView.findViewById(R.id.speed);
refresh = (ImageView) rootView.findViewById(R.id.refresh);
refresh.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//CALL ASYNCTASK HERE
}
});
return rootView;
}
回答1:
You can use a decoupled messaging system as EventBus or Otto. First fragment will be publisher and second subscriber. In the latter you'll start the AsyncTask.
Later on you can use the system anywhere in the app whenever you need to send an object from one component to another.
回答2:
Simply move the AsyncTask into its own public class and you can call it from wherever you like. Have a callback interface and implement that in the fragments where you are calling the AsyncTask.
回答3:
Create an interface for the Fragment class
public interface OnFragmentButtonListener{
onMyButtonClicked();
}
Now, have your activity hosting these fragments implement this interface.
In your OnClick method, have that call
((OnFragmentButtonListener)getActivity()).onMyButtonClicked();
Next create a method inside your Fragment Class hosting the AsyncTask inner class.
public void startAsyncTask(){
new LoadQueueTask.execute();
}
Inside the activity, you are forced to implement your interface method onMyButtonClicked(); In this method, get a handle to your fragment and call the startAsyncTask method in the fragment.
来源:https://stackoverflow.com/questions/26822697/call-inner-asynctask-from-outside-fragment