Yugo take you to fly Android Multi-threaded and asynchronous tasks--first article

Source: Internet
Author: User

I have been working for more than a year, specific points have been more than 3 months, internship early, premature by the society's ravages. In June this year, many graduates, and then to a relatively large company, the specific name is not said, is the sister super super more .... In school is the game, CX, and so on, but unconsciously after graduating with the students after the application, thanks to my first boss-Li Jinbo, Super Thank ~

OK, nonsense not much to say, the next turn on the Android multi-threading and asynchronous task learning, because the content is a bit more, a few blog to and everybody rip ~


Learn Android of course, can not avoid learning Java,java also have many threads in the synchronization problem between the thread and so on ~ design to the knowledge is also quite large, suggest small partners to see Preach Wisdom podcast Zhang Xiaoxiang java multi-threaded synchronization that several video, speak of is quite good ~, unfortunately, Xiang elder brother has gone, Why do programmers do not live long! Time enough, I will also share the experience of thread synchronization, of course, thank Cheung, I wish Cheung brother all well ~


We'll talk about the multi-threaded and asynchronous tasks of Android in 5 parts.

1:java Multithreading Basics

(1): Threadpoolexecutor

(2): Scheduleexecutor

(3): Thread Synchronization (Synchronized,lock,semaphore)

2: Threads that are used in Android

3: Components that are indispensable when using handler async

4: Use Asynctask to quickly implement asynchronous tasks

5: Where to use multithreading in the detection program


The first part, in the last chapter I will give you to explain the use of multithreading in Java and thread synchronization between the problem, let you heroes laughed at, because the meal has not eaten you eat more salt ~,


This blog we focus on the second part----the threads used in Android

In drawing this topic, we have to think of three questions:

1: Why use multithreading?

2: How do I use multi-threaded or asynchronous operations on Android?

3: Interaction between multithreading and interfaces

Let's start with the first question-why multithreading? We use multithreading often involves some complex IO operations (file operations, network operations, database operations), complex operations, and timed operations. Presumably everyone has encountered the application pop-up "unresponsive" dialog, because in the Android main thread timed out operation, too much blocking the main thread will cause the application to appear ANR waring~

Here is a small example of why you should use Multithreading: if we now have a demand, need to click the button when a dialog (dialog box), this dialog box shows 5 seconds after the automatic disappearance, how do we do it? If we call Dialog.show () in the button's click event, then call Thread.Sleep (5000), and finally call Dialog.dismiss (); Is it OK? The answer is NO! Because you will find this phenomenon, we seem to have not seen dialog~ from the beginning to the end, this is why?

The drawing in Android is thread insecure, and a lot of people will wonder if the thread is unsafe. Don't worry about this, because Android has only one drawing thread, which is the UI thread (the main thread). There is only one thread that does not have a thread security problem ~ Back to our problem, because the control in Android is drawn in the UI thread, when we call Dialog.show () This code, the distance dialog draw out there is a certain time interval, At this time we call Thread.Sleep (5000), let the main thread sleep for 5 seconds, brother Ah, the main thread have rested, but also draw a yarn! Of course it's out of sight ~ so we need to open a thread to let dialog go through 5 Seconds to disappear ~ (there are other ways, of course)

Understand why using multithreading, let's look at several ways to use multithreading or asynchronous operations

1:thread

2:handler

3:asynctask

4:asynctaskloader This class is available in API level 11, which is 3.0 (but V4 pack)

It is worth mentioning that the Asynctaskloader sub-class Cursorloader this is used to correlate the database to operate is also good ~ specific will be explained

Believe that we use the most is hander and Asynctaskloader, I usually use the most is the two ~, now the project involves the chat to use the Cursorloader, but feel still live ~

We do not worry ~,handler and asynctask back will focus on the analysis ~ The first article to everyone said a general outline, we know there are so several ways on it, don't worry ah, what is the DA ~

Finally, the third small question: How does multithreading interact with the interface? The options available in Android are:

1:activity.runonuithread (Runnable);

2:view.post (Runnable); View.postdelay (Runnable);

3:handler

4:asynctask

When threading interacts with the interface, we must strictly define the following two principles:

(1) do not block the UI thread

(2) Do not update the interface outside the UI thread

Tips:

1: For time-consuming operations, we should put it in a non-main thread to avoid blocking the main thread ~

2: In order to ensure a good user experience, recommended for more than 50ms operation, all use threading ~

Why is it that more than 50ms is being processed in the thread? is not causing the application to be unresponsive for 10 seconds? For everyone to calculate 1 seconds =1000ms,1000ms/50ms=20 fps, that is, 1 seconds to refresh the frame number of 20 frames, this is the human eye does not feel very much the number of frames, if less than 20 frames, you will feel the sliding page and other operations very stuttering ~ So less than 50ms for the user experience is very important ~

Below for everyone to put a small example, easy to understand, on the code ~

First the code to post the layout file ~

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" Fill_parent "Android: layout_height= "Fill_parent" > <button android:layout_width= "match_parent" android:layout_height= "Wrap_c Ontent "android:text=" from mainline loads download "android:id=" @+id/loadfrommainthread "/> <button android:layout _width= "Match_parent" android:layout_height= "wrap_content" android:text= "Download from async line loads 1" Androi D:id= "@+id/loadfromotherthread1"/> <button android:layout_width= "match_parent" android:layout_height= " Wrap_content "android:text=" from async line loads download 2 "android:id=" @+id/loadfromotherthread2 "/> <button Android Oid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "Loading pictures with Asyncthread "Android:id=" @+id/loadfRomasync "/> <imageview android:layout_width=" wrap_content "android:layout_height=" Wrap_cont Ent "android:id=" @+id/image "/></linearlayout>

The parent layout is linearlayout, there are 4 buttons in the vertical direction, the bottom is a imageview, used to display pictures ~

Next up is the Body Code section.

Package Com.example.xiaoyuandroidthread1;import Android.app.activity;import android.graphics.drawable.Drawable; Import Android.os.asynctask;import android.os.bundle;import Android.util.log;import Android.view.view;import Android.widget.imageview;import Java.io.ioexception;import Java.net.url;public class MyActivity extends Activity {pri    vate ImageView image;    public static final String URL = "Http://pic.sc.chinaz.com/files/pic/pic9/201501/apic9211.jpg";        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);        Image = (ImageView) Findviewbyid (r.id.image); Download the picture Findviewbyid (R.id.loadfrommainthread) directly in the main thread. Setonclicklistener (New View.onclicklistener () {@Ove                Rride public void OnClick (View v) {drawable drawable = loadimagefromnework (URL);            Image.setimagedrawable (drawable);        }        });      Download the image in the new thread that opens 1  Findviewbyid (R.ID.LOADFROMOTHERTHREAD1). Setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {New Thread (new Runnable () {@Override P                        ublic void Run () {drawable drawable = loadimagefromnework (URL);                    Image.setimagedrawable (drawable);            }}). Start ();        }        });            Download Picture 2 Findviewbyid (r.id.loadfromotherthread2) in the new thread that opens. Setonclicklistener (new View.onclicklistener () {                     @Override public void OnClick (View v) {New Thread (new Runnable () {@Override                        public void Run () {final drawable drawable = loadimagefromnework (URL); Image.post (New Runnable () {@Override public void R Un () {IMAGE.SEtimagedrawable (drawable);                    }                        });            }}). Start ();        }        }); Use Asynctask to download images Findviewbyid (r.id.loadfromasync). Setonclicklistener (New View.onclicklistener () {@Ove            Rride public void OnClick (View v) {new Downloadimagetask (). Execute (URL);    }        }); } private class Downloadimagetask extends asynctask<string,void,drawable>{@Override protected Draw        Able Doinbackground (String ... params) {return loadimagefromnework (params[0]);        } @Override protected void OnPostExecute (drawable drawable) {image.setimagedrawable (drawable);  }}//Use drawable to load pictures from the network private drawable loadimagefromnework (String imageUrl) {drawable drawable =        Null        try {drawable = Drawable.createfromstream (new URL (IMAGEURL). OpenStream (), "meinv.jpg"); } CatCH (ioexception e) {log.e ("Xiaoyu", E.getmessage ());        } if (drawable = = null) {LOG.E ("Xiaoyu", "drawable is null");        } else {log.e ("Xiaoyu", "drawable not NULL");    } return drawable; }}

Here to declare, click on the second button, the program will crash (this is normal ~), because the UI thread update ImageView, so the program crashes, this is for the program to demonstrate the effect ~

The first button to load a picture in the main thread, of course, this picture is very small, the fake piece is very large, it will cause the main thread blocking, resulting in the application anr~

The implementation logic of the third button is the same as the second button, the time-consuming operation to load the network data is placed in thread, but unlike the second button, the update UI is updated via the view post method after the drawable is obtained. So clicking on the third button will not cause the program to crash.

The fourth button updates the UI via Asynctask, which will be analyzed in detail ~

The method of loading the picture is also extremely simple, through drawable in the Createfromstream this method to implement, the first parameter passes a iostream, we pass the new URL (URL). OpenStream (); The second parameter is not necessary to pass, you can pass NULL, here is a random name ~

Finally, don't forget to declare permissions to access the network in the Androidmanifist file ~

The above is the entire content of this article, the next will be for everyone to continue to launch this series of blog ~

I will not give you a piece, I am not very convenient here ~

Test code Address: http://download.csdn.net/detail/ly985557461/8424333

Yugo take you to fly Android Multi-threaded and asynchronous tasks--first article

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.