Android AsyncTasks How to Check If activity is still running

前端 未结 8 1486
时光说笑
时光说笑 2021-02-07 04:25

I have used AsyncTasks with my application, in order to lazy download and update the UI.

For now my AsyncTasks updates the UI real simply:

8条回答
  •  醉酒成梦
    2021-02-07 05:05

    I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:

    volatile 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 than some of the solutions I have seen on SO.

提交回复
热议问题