AsyncTask 異步處理

複製代碼
 1 package com.ch.day8_asynctaskdemo;  2  3 import java.util.ArrayList;  4  5 import com.ch.myutils.NetWorkUtil;  6  7 import android.os.AsyncTask;  8 import android.os.Bundle;  9 import android.app.Activity; 10 import android.content.Context; 11 import android.util.Log; 12 import android.view.Menu; 13 import android.view.View; 14 import android.view.View.OnClickListener; 15 import android.widget.Button; 16 import android.widget.EditText; 17 18 public class MainActivity extends Activity { 19 private EditText name; 20 private EditText pass; 21 private Button login; 22  Context mcontext; 23 24  @Override 25 protected void onCreate(Bundle savedInstanceState) { 26  super.onCreate(savedInstanceState); 27  setContentView(R.layout.activity_main); 28 mcontext = this; 29  init(); 30  } 31 32 public void init(){ 33 name = (EditText) findViewById(R.id.username); 34 pass = (EditText) findViewById(R.id.userpass); 35 login = (Button) findViewById(R.id.login); 36 37 login.setOnClickListener(new OnClickListener() { 38  @Override 39 public void onClick(View v) { 40 String nameV = name.getText().toString(); 41 String passV = pass.getText().toString(); 42 43 //判斷網路是否暢通加權限 44 if(NetWorkUtil.isNetAvailable(mcontext)){//網絡暢通 45 //經過AsyncTask訪問服務器 46 47  new MyAsyncTask().execute(nameV,passV,NetWorkUtil.LOGIN_URL);//調用MyAsyncTask執行請求 48  } 49  } 50  }); 51  } 52  class MyAsyncTask extends AsyncTask<String, Integer, String>{ 53 // 後臺執行,比較耗時的操做均可以放在這裏 54 @Override 55 protected String doInBackground(String... params) {//params的類型和AsyncTask類的第一個泛型對應 56 // TODO Auto-generated method stub 57 String uname = params[0];//獲得用戶名 58 String upass = params[1];//獲得密碼 59 String url = params[2];//獲得url 60 String rs = NetWorkUtil.loginCheck_Get_HttpClient(uname, upass, url);//請求服務器。獲得結果 61 62 return rs;//把請求的結果傳遞到onPostExecute方法中 63 } 64 //至關於Handler 處理UI的方式,在這裏面能夠使用在doInBackground 獲得的結果處理操做UI 65 @Override 66 protected void onPostExecute(String result) {//result的類型和AsyncTask類的第三個泛型對應 67 // TODO Auto-generated method stub 68 login.setText(result); 69 //判斷登錄的結果,決定是否跳轉 70 71 // super.onPostExecute(result); 72 } 73 74  } 75 76 77 }
複製代碼
複製代碼
package com.ch.myutils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class NetWorkUtil { public static final String LOGIN_URL = "http://169.254.109.73:8080/serverof1407a/loginServlet"; public static boolean isNetAvailable(Context context){ //得到網絡管理器 ConnectivityManager connM = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = connM.getActiveNetworkInfo();//獲得網絡詳情 if(netInfo == null || !netInfo.isAvailable()) return false; return true; } public static String loginCheck_Get_HttpClient(String name,String pass,String url){ //經過StringBuffer來加工url StringBuffer sb = new StringBuffer(url); sb.append("?username="); sb.append(name); sb.append("&userpass="); sb.append(pass); String result = ""; HttpGet get = new HttpGet(sb.toString());//建立httpClient的get請求對象 //設置請求參數 HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5*1000); HttpConnectionParams.setSoTimeout(params, 5*1000); HttpClient client = new DefaultHttpClient(params);//建立HttpClient對象 try { HttpResponse res = client.execute(get);//執行請求,得到結果 if(res.getStatusLine().getStatusCode() == 200){ HttpEntity entity = res.getEntity();//得到相應結果,是一個HttpEntity對象 result = EntityUtils.toString(entity, "utf-8");//轉換爲字符串  } } catch (ClientProtocolException e) { // TODO Auto-generated catch block  e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block  e.printStackTrace(); } return result; } }
複製代碼
相關文章
相關標籤/搜索