Android AsyncTasks How to Check If activity is still running

前端 未结 8 1465
时光说笑
时光说笑 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.

    0 讨论(0)
  • 2021-02-07 05:07

    Check whether activity is running or not

     if (!isFinishing()) {
      // Do whatever you want to do
    }
    
    0 讨论(0)
  • 2021-02-07 05:14

    I will insist that you that if you Activity is not running why don't you cancel the AsyncTask? That would be a better and feasible solution. If you Application is running say you move from one Activity to another then it won't give error AFAIK.

    But, I would insist to cancel the AsyncTask then you'r Activity is not running, you can check AsyncTask is running or not,

    if(task != null && task.equals(AsyncTask.Status.RUNNING))
    task.cancel(true);
    
    0 讨论(0)
  • 2021-02-07 05:15

    You can cancel your asynctask in the activity's onDestroy

    @Override
    protected void onDestroy() {
        asynctask.cancel(true);
        super.onDestroy();
    }
    

    and when performing changes you check whether your asynctask has been cancelled(activity destroyed) or not

    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        if(!isCancelled()) {
             gender.setText(values[0]);
        }
    }
    
    0 讨论(0)
  • 2021-02-07 05:17

    As this part of one training on Android Developers suggests, keep a WeakReference on the UI element that needs to be updated after task is done and check if the reference is null before using it. This helps not only in checking if the UI is still around, but also does not prevent UI elements from being garbage collected.

    0 讨论(0)
  • 2021-02-07 05:17

    Shouldn't

    if (gender) {
       gender.setText(values[0]);
    }
    

    be enough?

    0 讨论(0)
提交回复
热议问题