AsyncTask execution need to cancel in same fragmen

2019-07-20 06:13发布

My Question is i need to open SAME FRAGMENT from Navigation Drawer's every List Item 's, and when fragment display, If AsynTask execution is On Going then AsyncTask execution should be cancel.

How can i do it?

I tried so many ways to accomplish this but i failed everytime.

I used asynctaskObject.cancel(true);

So Can anybody please answer. i hope i'll get the result.

Thanks in advance. :)

2条回答
ゆ 、 Hurt°
2楼-- · 2019-07-20 06:15

i found solution of my problem.

We just need to make request in onStop method like below :

@Override
public void onStop() {
    super.onStop();
    if(asyncTaskObject!=null){
        asyncTaskObject.cancel(true);
    }
}    

This way whenever we request from Navigation Drawer's List Item on Same Fragment, at that time fragment call onStop() method and i just call task.cancel(true);

And Thanks to @MysticMagic. i resolved this issue from your given link.

查看更多
爷、活的狠高调
3楼-- · 2019-07-20 06:19

For forceful cancel() to work, you will need to check if its cancelled in doInBackground.

@Override
protected String doInBackground(String... params) 
{
    . 
    .
    if(isCancelled()){
        break;
    }
    .
}

Refer this: Why Android AsyncTask doesn’t stop after being cancelled

Hope it helps.

查看更多
登录 后发表回答