ANR caused by Input dispatching timed out - while trying to get my public IP address

前端 未结 1 496
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 18:44

I get the following complete error message: Input dispatching timed out (Waiting to send non-key event because the touched window has not finished processing certain input event

1条回答
  •  别那么骄傲
    2021-02-13 19:22

    I think your problem is that you're calling AsyncTask.get() right after you call GetIP_WAN().execute(). I assume that you're calling GetIP_WAN().execute() on the UI thread. If it's in an onClick callback or a BroadcastReceiver it most certainly is. So what I believe is happening is your GetIP_WAN task is correctly executing on a background thread completing but the get() call is attempting to retrieve the data that will get returned from doInBackground(). But that call (get()) will NEVER return before doInBackground and maybe onPostExecute(...) returns, thus causing blocking on the UI thread. If you read the documentation for get inside of the AsyncTask class it says

    /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */

    Ironically, you are negating the purpose of you AsnycTask. Even though the work is taking place on the background thread, you are forcing the UI thread to wait for the work to complete before any additional processing on the UI thread can complete. The Android OS handles creating a ANR dialog when it detects the UI/Main thread has been blocking for 5 seconds.

    I assume you are calling get so you can get your data from GetIP_WAN, so you can manipulate/display it on the UI thread. What I recommend is you pass some form of reference to the owning activity or fragment into the GetIP_WAN and when the task completes and fires onPostExecute(...) which will be fired on the UI/Main thread, you act upon the activity or fragment to update it's UI with the data you downloaded in doInBackground(...). One pattern I'd recommend is passing a Handler reference that's wrapped inside of a WeakReference into GetIP_WAN and in onPostExecute(...), send an empty message indicating that the work was completed and it's safe to call GetIP_WAN.get().

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