一般获取验证码,用户登录验证,上传头像,获取消息,发消息,评论 都可以使用
1.先上官网实例代码
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }
上面代码是:下载文件的AsyncTask
doInBackground 方法:
根据传入的url,下载文件,显示下载进度,判断是否取消下载,返回。
onProgressUpdate:
显示下载进度?
onPostExecute:
下载完成,执行该方法。
new DownloadFilesTask().execute(url1, url2, url3);
上面是调用 DownloadFilesTask。
2.AsyncTask 参数分析
android.os.AsyncTask<Params, Progress, Result>
Params 定义onProgressUpdate传入参数类型,Result 是onProgressUpdate返回参数类型
Progress 定义onProgressUpdate
Result 是onPostExecute传入参数类型。
3.下面是一个登录实例
package com.lanbeizi.secret.net; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import android.os.AsyncTask; import com.lanbeizi.secret.Config; public class NetConnection { public NetConnection(final String url,final HttpMethod method,final SuccessCallback successCallback,final FailCallback failCallback,final String ... kvs){ new AsyncTask<Void,Void,String>(){ @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub StringBuffer paramsStr = new StringBuffer(); for(int i=0;i < kvs.length ; i+=2){ paramsStr.append(kvs[i]).append("=").append(kvs[i+1]).append("&"); } try { URLConnection uc ; switch(method){ case POST: // post 方式上传参数,以流的方式上传 uc = new URL(url).openConnection(); uc.setDoOutput(true); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(uc.getOutputStream(),Config.CHARSET)); bw.write(paramsStr.toString()); bw.flush(); break; default: //get 方式 将参数写入url 不安全 uc = new URL(url+"?"+paramsStr.toString()).openConnection(); break; } System.out.println("Request url: " + uc.getURL()); System.out.println("Request data: " + paramsStr); //按行读取数据 BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream(),Config.CHARSET)); String line = null; StringBuffer result = new StringBuffer(); while((line=br.readLine())!= null){ result.append(line); } System.out.println("Result : " + result); return result.toString(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // 传参 result 是 doInBackground 的返回值 @Override protected void onPostExecute(String result) { if(result != null) { if (successCallback != null){ successCallback.onSuccess(result); } }else { if (failCallback != null){ failCallback.onFail(); } } super.onPostExecute(result); } }.execute(); } public static interface SuccessCallback{ void onSuccess(String result); } public static interface FailCallback{ void onFail(); } }
package com.lanbeizi.secret.net; import org.json.JSONException; import org.json.JSONObject; import com.lanbeizi.secret.Config; public class Login { public Login(String phone_md5,String code, final SuccessCallback successCallback,final FailCallback failCallback){ new NetConnection(Config.SERVER_URL, HttpMethod.POST,new NetConnection.SuccessCallback() { @Override public void onSuccess(String result) { try { JSONObject obj = new JSONObject(result); switch (obj.getInt(Config.KEY_STATUS)) { case Config.RESUTL_STATUS_SUCCESS: if(successCallback != null){ successCallback.onSuccess(obj.getString(Config.KEY_TOKEN)); } break; default: if(failCallback != null){ failCallback.onFail(); } break; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); if(failCallback != null){ failCallback.onFail(); } } } }, new NetConnection.FailCallback() { @Override public void onFail() { if(failCallback != null){ failCallback.onFail(); } } } , Config.KEY_ACTION,Config.ACTION_LOGIN,Config.KEY_PHONE_MD5,phone_md5,Config.KEY_CODE,code); } public static interface SuccessCallback{ void onSuccess(String token); } public static interface FailCallback{ void onFail(); } }
package com.lanbeizi.secret.atys; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.lanbeizi.secret.Config; import com.lanbeizi.secret.R; import com.lanbeizi.secret.net.GetCode; import com.lanbeizi.secret.net.Login; import com.lanbeizi.secret.tools.MD5Tool; public class AtyLogin extends Activity { private EditText etPhone = null; private EditText etCode = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.aty_login); etPhone = (EditText) findViewById(R.id.etPhoneNum); etCode = (EditText) findViewById(R.id.etCode); findViewById(R.id.btnGetCode).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(TextUtils.isEmpty(etPhone.getText())){ Toast.makeText(AtyLogin.this,R.string.phone_num_can_not_be_empty, Toast.LENGTH_LONG).show(); return; } final ProgressDialog pd = ProgressDialog.show(AtyLogin.this,getResources().getString( R.string.connecting), getResources().getString(R.string.connecting_to_server)); new GetCode(etPhone.getText().toString(), new GetCode.SuccessCallback() { @Override public void onSuccess() { // TODO Auto-generated method stub pd.dismiss(); Toast.makeText(AtyLogin.this,R.string.succ_to_get_code, Toast.LENGTH_LONG).show(); } }, new GetCode.FailCallback() { @Override public void onFail() { pd.dismiss(); // TODO Auto-generated method stub Toast.makeText(AtyLogin.this,R.string.fail_to_get_code, Toast.LENGTH_LONG).show(); } });// end GetCode } }); //end findViewById(R.id.btnGetCode) findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(TextUtils.isEmpty(etPhone.getText().toString())){ Toast.makeText(AtyLogin.this,R.string.phone_num_can_not_be_empty, Toast.LENGTH_LONG).show(); return; } if(TextUtils.isEmpty(etCode.getText().toString())){ Toast.makeText(AtyLogin.this,R.string.code_can_not_be_empty, Toast.LENGTH_LONG).show(); return; } final ProgressDialog pd = ProgressDialog.show(AtyLogin.this,getResources().getString( R.string.connecting), getResources().getString(R.string.connecting_to_server)); new Login(MD5Tool.md5(etPhone.getText().toString()), etCode.getText().toString(), new Login.SuccessCallback() { @Override public void onSuccess(String token) { pd.dismiss(); Config.cacheToken(AtyLogin.this, token); Config.cachePhoneNum(AtyLogin.this, etPhone.getText().toString()); Intent i = new Intent(AtyLogin.this,AtyTimeLine.class); i.putExtra(Config.KEY_TOKEN, token); i.putExtra(Config.KEY_PHONE_NUM, etPhone.getText().toString()); startActivity(i); finish();// 关闭当前登陆的ACTIVITY 这样按返回键就不会回到登陆页面了 } }, new Login.FailCallback() { @Override public void onFail() { pd.dismiss(); Toast.makeText(AtyLogin.this, R.string.fail_to_login, Toast.LENGTH_LONG).show(); } }); // end new Login } });// end findViewById(R.id.btnLogin) } }
三个类 NetConnection.class Login.class AtyLogin.class
NetConnection.class 是网络链接通用类
Login.class 登录网络通信类
AtyLogin.class 登录窗口