'How to stop an AsyncTask in a Fragment after the Application closes
How to stop AsyncTask in Fragment class after closing the application?
MainActivity class
public class MainActivity extends FragmentActivity {
}
BaseFragment class extends by Fragment
public class BaseFragment extends Fragment {
public MainActivity mActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (ChatActivity)this.getActivity();
}
public boolean onBackPressed(){
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
Fragment class
public class Fragment1 extends BaseFragment{
private Update task;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
toCallAsynchronous();
return inflater.inflate(R.layout.activity_online_korisnici, container,
false);
}
public void toCallAsynchronous() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
task =new Update();
// PerformBackgroundTask this class is the class that extends AsynchTask
task.execute("");
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 50000 ms
}
private class Update extends AsyncTask<Object, Object, List<Object>>{
@Override
protected List<Object> doInBackground(Object... params) {
}
@Override
protected void onPostExecute(List<Object> result) {
}
}
}
Solution 1:[1]
task.cancel() will do it. Be sure to include frequent checks to isCancelled() in your onBackground() as well as in onPostExecute() to avoid accessing/updating UI which is no longer there.
Solution 2:[2]
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the activity. After researching the problem on Stack Overflow, I adopted the following solution:
boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler and less error prone than some of the solutions I have seen on SO.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 323go |
| Solution 2 | IanB |
