Skip to content Skip to sidebar Skip to footer

Android Io Operations On Main Thread

My question is two fold: Is doing IO operations on main thread in Android advisable or does it have a potential to crash my app. If doing IO operation on main thread not ideal, wh

Solution 1:

Is doing IO operations on main thread in Android advisable or does it have a potential to crash my app.

as explained in documentation its not advisable. You might get bad user experience. Longer operations on UI thread (~5s), will result in ANR (application not responding) dialog - which results in crashing your app. Also IO operations like network communications will result in immediate exception being thrown by API.

If doing IO operation on main thread not ideal, what other frameworks I can use so that when my app loads it can do some basic IO file reads and can store the values in variables.

lots of, for basic IO file reads you can use AsyncTask:

  • AsyncTask - for short operations - like reading file + parsing it. You have to manage its life time on your own - ie. if used in activity and it gets destroyed due to config change.

  • Loaders - was supposed to replace AsyncTask as easier to be managed component inside Activities. Its management is being done by framework.

  • Executor - this is java class which executes your code on thread pools. You have to manage its life time on your own. Ie. when having config changes in activity.

  • Services it does not create its own thread, but allows you to perform long operations in background.

  • IntentService - service that creates its own thread and processes your tasks in queue

Solution 2:

IO operations are never advisable since it fay take some time to fetch the file and such.

IO operations should be done using a separate thread and an AsyncTask can help you with that

Post a Comment for "Android Io Operations On Main Thread"