Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Android thread mechanism --AsyncTask     - HAProxy Windows version of the compiler and its application in the CORS (Server)

- The difference between vi and nano (Linux)

- Install Visual Studio Code in Ubuntu (Linux)

- Boost notes --Thread - problems encountered in the initial use on Ubuntu (Programming)

- How VirtualBox and VMware virtual machine conversion (Linux)

- OpenGL Superb Learning Notes - Depth Texture and Shadows (Programming)

- How to protect the Apache website under Linux system (Linux)

- NAT (network address translation) Realization (Linux)

- Git uses a basic tutorial (Linux)

- Connect to the Oracle Database Help class (Database)

- Protection Docker container Notice (Server)

- CentOS install expect (Linux)

- Ubuntu 15.04 installed Nvidia Quadro series graphics driver (Linux)

- Java coding conventions (Programming)

- Elaborate .NET Multithreading: Concepts (Programming)

- Linux fixes fatal error: x264.h: No such file or directo (Linux)

- New experience Budgie (Budgerigar) desktop environment (Linux)

- Compile and install Memcached can not find GCC (Programming)

- Linux module mechanism of (Programming)

- Ubuntu Gitolite management Git Server code base permissions (Server)

 
         
  Android thread mechanism --AsyncTask
     
  Add Date : 2018-11-21      
         
         
         
  For Android Why use multiple threads, because after Android4.0, Google provides the network operator is not allowed in the main thread of execution, whereby there is a multi-threaded mechanism, there is a learning experience JAVA friends must know multithreading What is meant, simply, that is, in the Java program, main () function is to open the main thread of this program, but we have to do some time-consuming operation and do not want to affect the implementation of the main thread, which we tend to Create a sub-thread by thread object to perform. Simply put, a program has only one main thread, the main thread can have more than one. In the Android world, too, belong to a single-threaded model Android, time-consuming operations must be performed in a non-main thread, and therefore Google in order to facilitate the use of threads we offer a AsyncTask multithreaded operation target for us.

Another point to note for Android using threads, which is the Android UI updates are not allowed in the child thread, some believe that many beginners encountered this problem, how to solve it? Activity in, we can

new Thread (new Runnable () {
            
            @Override
            public void run () {
                Log.v ( "abc", "child thread execution");
                runOnUiThread (new Runnable () {
                    
                    @Override
                    public void run () {
                        Log.v ( "abc", "return to the main thread of execution");
                    }
                });
            }
        .}) Start ();

To achieve our performance, but one thing to note is that in the Fragement, runOnUiThread () can not be used, so we use a little attention at the time of click. Of course, we can also Android Handler + Messager to complete the multi-threaded operation, for a use here, in the previous blog has to introduce, will not go into details in the following, we began to introduce the focus of this Title: AsyncTask use.

AsyncTask < Parans, Progress, Result> is an abstract class, we need to implement this abstract class before you can use it for three parameters: Parans: Start the task parameter type input; progress: a background task in the return value type; result: result type after the background task is completed return.

Construction callback method AsyncTask subclasses: 1, doInBackground: must be rewritten, asynchronous thread will perform background tasks to be completed; 2, onPreExecute: Processed before performing background operation is invoked by the user to complete some initialization; 3, onPostExecute: when after doInBackground () is complete, the system will automatically call and doInBackground () return value after execution passed to onPostExecute () method, is simply, doInBackground () to complete the time-consuming operation, the result of a cross onPostExecute () method to update UI; 4, onProgressUpdate: in doInBackground () method, call publishProgress () after the progress in the implementation method, the update task, it will trigger the process.

Having said that, I believe there is still some doubt in your heart, we adopted the following two simple Android applet, as we introduce the specific use of AsyncTask:

a, AsyncTask execution order is an abstract method:

1, create a subclass object AsyncTask:

public class MyAsyncTask extends AsyncTask < Void, Void, Void> {

    @Override
    protected void onPreExecute () {
        super.onPreExecute ();
        Log.v ( "abc", "onPreExecute");
    }

    @Override
    protected Void doInBackground (Void ... arg0) {
        Log.v ( "abc", "doInBackground");
        publishProgress (arg0);
        return null;
    }
    
    @Override
    protected void onPostExecute (Void result) {
        super.onPostExecute (result);
        Log.v ( "abc", "onPostExecute");
    }
    
    @Override
    protected void onProgressUpdate (Void ... values) {
        super.onProgressUpdate (values);
        Log.v ( "abc", "onProgressUpdate");
    }

}

2, the call to the child thread in MainActivity, make the implementation of:

public class MainActivity extends Activity {
    
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        new MyAsyncTask () execute ();. // boot Execution

}

3, after the execution of printing log log:

Through this log information is not to solve the doubts of your mind, let's look at an example using the picture AsyncTask load the network.

b, load the network picture:

1, first create a layout file hosting Activity xml:

 

< RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
    xmlns: tools = "http://schemas.android.com/tools"
    android: layout_width = "match_parent"
    android: layout_height = "match_parent"
    android: layout_margin = "10dp"
    tools: context = ". MainActivity">

    < ImageView
        android: id = "@ + id / img"
        android: layout_width = "match_parent"
        android: layout_height = "match_parent"
        />
    < ProgressBar
        android: id = "@ + id / progressbar"
        android: layout_width = "wrap_content"
        android: layout_height = "wrap_content"
        android: visibility = "gone"
        android: layout_centerInParent = "true"
        />

< / RelativeLayout>

Layout file is simply a ImageView + ProgressBar, loading ImageView us to remind the user to wait through ProgressBar.

2, create our Activity objects:

 

public class AsyncTaskImager extends Activity {
    
    private ProgressBar pb;
    private ImageView image;
    private static final String url = "upload / 2015_06 / 150628161776433.png";
    
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.imager);
        init ();
        new ImageAsyncTask () execute (url).;
    }

    private void init () {
        pb = (ProgressBar) findViewById (R.id.progressbar);
        image = (ImageView) findViewById (R.id.img);
    }
    
    class ImageAsyncTask extends AsyncTask < String, Void, Bitmap> {

        @Override
        protected void onPreExecute () {
            super.onPreExecute ();
            pb.setVisibility (View.VISIBLE);
        }
        
        @Override
        protected Bitmap doInBackground (String ... params) {
            Bitmap bitmap = null;
            URLConnection conn = null;
            String url = params [0];
            try {
                conn = new URL (url) .openConnection ();
                InputStream in = conn.getInputStream ();
                BufferedInputStream bis = new BufferedInputStream (in);
                bitmap = BitmapFactory.decodeStream (bis);
            } Catch (MalformedURLException e) {
                e.printStackTrace ();
            } Catch (IOException e) {
                e.printStackTrace ();
            }
            return bitmap;
        }
        
        @Override
        protected void onPostExecute (Bitmap result) {
            super.onPostExecute (result);
            pb.setVisibility (View.GONE);
            image.setImageBitmap (result);
        }
    }
    
}

 

Here we have the great merit basically completed, and finally do not forget to look in AndroidManifest.xml statement.

3. Add a network operating authority:

< Uses-permission android: name = "android.permission.INTERNET" />

Because we need to use to connect to the network, so we need to add a network access in AndroidManifest.xml.
     
         
         
         
  More:      
 
- IBM Data Studio to use ---- window displays all rows (Database)
- CentOS 5.8 (64) Python 2.7.5 installation error resolved (Linux)
- Linux character device - a simple character device model (Linux)
- Shell Script: create a function and specify a directory for download (Programming)
- ThinkPad X220 Ubuntu 14.10 installed on fingerprint recognition (Linux)
- Package the Python script file into an executable file (Programming)
- Linux crontab command format example (Linux)
- Advanced Linux security settings (Linux)
- Vi (Vim) keyboard map and its basic commands (Linux)
- Linux file system data file deletion problem space is not freed (Database)
- Zabbix monitoring disk IO status (Server)
- Compile and install the latest version of Redis Stable (Database)
- To update Python version under CentOS system (Linux)
- Linux Network Security Tips Share (Linux)
- Linux file system management partition, format, mount - label mount (Linux)
- Linux environment variable configuration and save places (Linux)
- Turning off the interface eth0: error: Disconnect the device 'eth0' (Linux)
- Linux Kernel 4.2.2 compiler installation tutorial (Linux)
- Ubuntu program using the Sound Recorder (Linux)
- CentOS7 compile and install Tengine + PHP + MariaDB notes (Server)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.