Android wait AsyncTask to finish

前端 未结 4 853
忘掉有多难
忘掉有多难 2020-12-04 15:47

I have a function, AppHelper.isOnline(Context context), I call in various parts of my application to check that a session didn\'t timeout before making an HTTP

4条回答
  •  星月不相逢
    2020-12-04 16:14

    Rafiq's response did not work for me - the app hung. I think the reason has to do with the nature of isCancelled(): "Returns true if this task was cancelled before it completed normally." If the task completes normally (i.e. is not cancelled) then while(!task.isCancelled()) { } will loop forever.

    To solve this create a Boolean flag that you instatiate to false and then flip to true in task.onPostExecute(). Then do while(!flag) { } before switching Activities. Additionally, if you'd like to give the main thread a 'break' to let the AsyncTask process a little faster, you can do try this:

    while (!flag) {
        try { Thread.sleep(100); }
        catch (InterruptedException e) { e.printStackTrace(); }
    }
    

    It seems to be working well for me.

提交回复
热议问题