android非同步類AsyncTask的簡單使用

來源:互聯網
上載者:User

標籤:android   style   blog   class   code   java   

Android為了降低這個開發難度,提供了AsyncTask。AsyncTask就是一個封裝過的背景工作類,顧名思義就是非同步任務,更通俗地說就是一個執行背景工作的線程

而且他還會自動通知主線程更新UI

 

優點:

  結構清晰,容易理解。

缺點

  代碼量稍大

 

下面直接看代碼

 1 private class AsyncLogin extends AsyncTask<Void,Integer,Boolean>{ 2         private EditText passwordEdit; 3         private EditText studentIdEdit; 4         public boolean isClose=false;      //建構函式 5         public AsyncLogin(EditText passwordEdit, EditText studentIdEdit) { 6             super(); 7             this.passwordEdit = passwordEdit; 8             this.studentIdEdit = studentIdEdit; 9         }10         11         private boolean checkResultCode(String code){12             String message=codeToResult.get(code);13             if(dialog.isShowing())14                 dialog.dismiss();15             if(message==null){16                 return true;17             }else{18                 Toast.makeText(MainActivity.this,     19                         message,     20                         Toast.LENGTH_LONG).show(); 21                 return false;22             }23         }24         25         private void intentJump(){26             if(!isClose){27                 Intent intent = new Intent(MainActivity.this,CourseListActivity.class);28                 intent.putExtra("sessionId", MainActivity.this.sessionId);29                 intent.putExtra("strUserName", this.studentIdEdit.getText().toString());30                 MainActivity.this.startActivity(intent);31                 MainActivity.this.finish();32             }33         }34       //後台線程完成後調用此方法,在此方法中可以更新主線程UI35         @Override36         protected void onPostExecute(Boolean result) {37             super.onPostExecute(result);38             if(result){39                 if(checkResultCode(MainActivity.this.sessionId))40                     intentJump();41             }else{42                 checkResultCode("000");43             }44         }45         //背景工作,主要完成工作量大的任務46         @Override47         protected Boolean doInBackground(Void... params) {48             String sessionId="";49             50             51             try{52                 Thread.sleep(5000);53                 sessionId = webService.CheckLogin(54                         this.studentIdEdit.getText().toString(),55                         this.passwordEdit.getText().toString());56             }catch(Exception e){57                 e.printStackTrace();58                 return false;59             }60             MainActivity.this.sessionId=sessionId;61             return true;62         }         //開始執行前調用該方法63         @Override  64         protected void onPreExecute() {  65             super.onPreExecute();  66              dialog = new ProgressDialog(MainActivity.this);  67              dialog.setCancelable(true);68              dialog.setMessage("正在登入,請等待..");69              dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {70                 @Override71                 public void onCancel(DialogInterface dialog) {72                     if(asycLogin!=null)73                         asycLogin.cancel(true);74                 }75              });76              dialog.show();77         }78     }

 

new AsyncLogin(passwordEdit,studentIdEdit).execute();//開始任務

下面是介面方法

 1、doInBackground(Params…) 後台執行,比較耗時的操作都可以放在這裡。注意不能直接操作UI。

 2、onPostExecute(Result)  處理UI的方式,這裡面可以使用在doInBackground 得到的結果處理操作UI。

 3、onProgressUpdate(Progress…)   可以使用進度條增加使用者體驗度。 此方法在主線程執行,用於顯示任務執行的進度。

 4、onPreExecute()        這當任務執行之前開始調用此方法,可以在這裡顯示進度對話方塊就好像上面代碼一樣。

 5、onCancelled()          使用者調用取消時,調用該方法

 

注意事項

     AsynTask的執行個體必須在UI thread中建立。

   不要主動調用任何介面方法。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.