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; } }