简体   繁体   中英

How to avoid the ANR dialog Application Not Responding

I'm working on an Android app, which uses an online service, which I need to load my Fragments. Basically, I have a menu, and each button replaces a Fragment underneath. When I click a button, the fragment starts being replaced, and if I press another button from my keyboard on the meantime, I get the Application Not Responding dialog, and then I click Wait, and my Fragment loads successfully.

Is there a way to prevent that from happening? My app will always take a few seconds to load, because of the web service. I read on Google, that I could use AsyncTask , and finish the loading on the doOnBackground method.. I don't know if that works, but I can't even try, because it won't let me change the view there, it throws an error about only the original thread can change the views. And I need the service to finish loading my view, so I can't even do the service with the AsyncTask.

I'm running out of ideas now! there has to be a way to do this. I appreciate suggestions!

Is there a way to prevent that from happening?

Yes: don't take so long on the main application thread. Use StrictMode to identify likely culprits (disk I/O, network I/O), and use Traceview to find out what else you are doing that might be taking too long.

My app will always take a few seconds to load, because of the web service.

That should be done in a background thread.

I read on Google, that i could use AsyncTask, and finish the loading on the DoOnBackground method.. I don't know if that works, but I can't even try, because it won't let me change the view there, it throws an error about only the original thread can change the views

Which is why you update the views from the onPostExecute() method, as is described in the documentation for AsyncTask .

您必须在 AsyncTask 的 onPostExecute() 函数中更改 ui。

Never execute a database operation or content provider operation in the context of the main thred. sooner or later you will be running into application Not Responding errors. the ANRs are not a good practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM