Question

I could access all the fragments objects in the activity .. but I want when click on button in Fragment A to stop the running AsyncTask in Fragment B .. how is possible ?

Was it helpful?

Solution

Fragments should not directly interact with on another; it is the Activity's task to manage Fragments.

That being said, you could use an event bus like Otto, to send "messages" to other parts of your application.

It differs from a Broadcast Receiver because there is no IPC overhead, sort of like using LocalBroadcastManager, but more reusable.

You can also use interfaces, but why do so when you can use an event bus and have components as loosely coupled as possible.

OTHER TIPS

Firstly, keep a reference of the task you fire off. You can then use AsyncTask.cancel to cancel the task when the button is pressed. Cancelling here just prevents onPostExecute from being called after doInBackground and results in onCancelled being called instead.

However, if you need to cancel the task during doInBackground, you can extend AsyncTask with your own class and use a boolean and a setter. Depending on the nature of your task, you can check the boolean at different points in doInBackground and handle cancellation appropriately.

It may also be simpler to use lifecycle callbacks such as onDestroyView or onDetach (on the first fragment) to cancel the task.

I will prefer communicating using interfaces, same as this link,

You need to define a interface for Stoping AsyncTask, on receiving callback from Fragment B to stop AsyncTask, your activity can ask fragment A to stop AsyncTask.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top