Asynctask is a good solution for background operations that have a short life cycle and need to show progress and results on the UI. However, when activity restarts, this operation will not persist, that is, the Asynctask will be canceled when the device's direction changes, causing activity to be destroyed and recreated. For background operations with long lifecycles, such as downloading data from the Internet, using service components is a better choice.
1 Private classMyasynctaskextendsAsynctask<string, Integer, string> {2 @Override3 protectedstring Doinbackground (String ... parameter) {4 //Moved to a background thread.5String result = "";6 intmyprogress = 0;7 8 intInputlength = parameter[0].length ();9 Ten //Perform Background Processing task, update myprogress] One for(inti = 1; I <= inputlength; i++) { AMyprogress =i; -result = result + Parameter[0].charat (inputlength-i); - Try { theThread.Sleep (100); -}Catch(Interruptedexception e) {} - publishprogress (myprogress); - } + - //Return The value to being passed to OnPostExecute + returnresult; A } at - @Override - protected voidOnprogressupdate (Integer ... progress) { - //Synchronized to UI thread. - //Update progress bar, Notification, or other UI elements -Asyncprogress.setprogress (progress[0]); in } - to @Override + protected voidOnPostExecute (String result) { - //Synchronized to UI thread. the //Report results via UI Update, Dialog, or notifications * Asynctextview.settext (result); $ }Panax Notoginseng } -
Executes an asynchronous task. Each Asynctask instance can be executed only once. If you try to invoke execute for the second time, an exception is thrown.
1 Private void Executeasync () {2 /** 3 * Listing 9-12:executing an asynchronous task4 */ 5 String input = "Redrum ... redrum"; 6 New 7 }
Android development tool Class 15_ Myasynctask