Android: Activity taking too long to display because of web service Http Request

前端 未结 6 605
野性不改
野性不改 2021-01-28 03:17

One of my activities make a http request to a webservice to get some weather data when I start the application.

The issue that the activity will take 3-4 seconds to disp

6条回答
  •  悲哀的现实
    2021-01-28 04:06

    The time for your response is unpredictable - your network connection can be very poor and take seconds to transfer a few bytes. So the correct way to do this ( as you propose ) is to use thread. In our case android provides very useful class to handle this situations - AsynTask. After you read the docs you will notice that it has 3 very powerful methods that can help you

    1. onPreExecute runs in the ui thread - very helpful to show some spinner or some progress indicator to show the user that you are doing some work in background
    2. doInBackground runs in background - do your background work here
    3. onPostExecute runs in the ui thread- when your are done with your background work hide the progress and update the gui with the newly received data.

提交回复
热议问题