Android multi-threaded data loading

     We know that the UI thread of android is the main thread of android, and the main thread is thread-safe. Some time-consuming threads, such as downloading, uploading or parsing large files, cannot be placed in the main thread. Why do you say this? Because the time-consuming operation in the main thread will cause the interface to get stuck, resulting in ANR (application unresponsive), ANR gives the customer a very bad experience, and as a programmer, try to avoid this situation. How do we do it? In fact, we can use multi-threading to solve. For example, we can start a new thread to do this time-consuming operation without affecting the interface loading of the main thread. Here is an example to illustrate:

  public class HandlerTest extends Activity{

        private Handler handler;

        private Runnable runnable = new Runnable {

                   public void run{

                           initViews(); //Big data loading

                   }

        }

        public void onCreate(){

                   super.savedInstance (....);

                   handler = new Handler ();

                   // initViews(); easy to get stuck if loaded like this

                 

                   //We use another method to achieve

                  handler.postDelayed(runnable,1000); Open another thread to load data

        }

 

       public void initViews(){

                    .......

                    .......

                    ...... //load a lot of data

           }

 

 

   The above multi-threaded method can avoid causing ANR and can also achieve fast loading!

                     

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325921825&siteId=291194637