歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android Http異步請求 Callback

Android Http異步請求 Callback

日期:2017/3/1 10:52:35   编辑:Linux編程

之前一直在用HTML5開發移動本地應用,後來發現,實際上HTML5開發的本地應用,開發效率高,而且跨平台,但是體驗,相應無法和原生應用,還有一定差距。

開發HTML5和遠程交互,采用JSONP,是異步方式。Android的異步方式不太一樣,采用的是多線程和Handler的方式處理。


1 首先是HttpConnection,方法包括HttPost, HttpGet

  1. package com.juupoo.common;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.client.methods.HttpPost;
  10. import org.apache.http.impl.client.DefaultHttpClient;
  11. import org.apache.http.message.BasicNameValuePair;
  12. import org.apache.http.params.BasicHttpParams;
  13. import org.apache.http.params.HttpConnectionParams;
  14. import org.apache.http.params.HttpParams;
  15. import org.apache.http.util.EntityUtils;
  16. import android.os.Bundle;
  17. import android.os.Handler;
  18. import android.os.Message;
  19. /**
  20. * Asynchronous HTTP connections
  21. *
  22. * @author Greg Zavitz & Joseph Roth
  23. */
  24. public class HttpConnection implements Runnable {
  25. public static final int DID_START = 0;
  26. public static final int DID_ERROR = 1;
  27. public static final int DID_SUCCEED = 2;
  28. private static final int GET = 0;
  29. private static final int POST = 1;
  30. private static final int PUT = 2;
  31. private static final int DELETE = 3;
  32. private static final int BITMAP = 4;
  33. private String url;
  34. private int method;
  35. private String data;
  36. private CallbackListener listener;
  37. private HttpClient httpClient;
  38. // public HttpConnection() {
  39. // this(new Handler());
  40. // }
  41. public void create(int method, String url, String data, CallbackListener listener) {
  42. this.method = method;
  43. this.url = url;
  44. this.data = data;
  45. this.listener = listener;
  46. ConnectionManager.getInstance().push(this);
  47. }
  48. public void get(String url) {
  49. create(GET, url, null, listener);
  50. }
  51. public void post(String url, String data, CallbackListener listener) {
  52. create(POST, url, data, listener);
  53. }
  54. public void put(String url, String data) {
  55. create(PUT, url, data, listener);
  56. }
  57. public void delete(String url) {
  58. create(DELETE, url, null, listener);
  59. }
  60. public void bitmap(String url) {
  61. create(BITMAP, url, null, listener);
  62. }
  63. public interface CallbackListener {
  64. public void callBack(String result);
  65. }
  66. private static final Handler handler = new Handler() {
  67. @Override
  68. public void handleMessage(Message message) {
  69. switch (message.what) {
  70. case HttpConnection.DID_START: {
  71. break;
  72. }
  73. case HttpConnection.DID_SUCCEED: {
  74. CallbackListener listener = (CallbackListener) message.obj;
  75. Object data = message.getData();
  76. if (listener != null) {
  77. if(data != null) {
  78. Bundle bundle = (Bundle)data;
  79. String result = bundle.getString("callbackkey");
  80. listener.callBack(result);
  81. }
  82. }
  83. break;
  84. }
  85. case HttpConnection.DID_ERROR: {
  86. break;
  87. }
  88. }
  89. }
  90. };
  91. public void run() {
  92. // handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
  93. httpClient = getHttpClient();
  94. try {
  95. HttpResponse httpResponse = null;
  96. switch (method) {
  97. case GET:
  98. httpResponse = httpClient.execute(new HttpGet(
  99. StaticInfos.Server_URL + url));
  100. break;
  101. case POST:
  102. HttpPost httpPost = new HttpPost(StaticInfos.Server_URL
  103. + url);
  104. List<NameValuePair> params = new ArrayList<NameValuePair>();
  105. BasicNameValuePair valuesPair = new BasicNameValuePair("args",
  106. data);
  107. params.add(valuesPair);
  108. httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
  109. httpResponse = httpClient.execute(httpPost);
  110. if (isHttpSuccessExecuted(httpResponse)) {
  111. String result = EntityUtils.toString(httpResponse
  112. .getEntity());
  113. this.sendMessage(result);
  114. } else {
  115. this.sendMessage("fail");
  116. }
  117. break;
  118. }
  119. } catch (Exception e) {
  120. this.sendMessage("fail");
  121. }
  122. ConnectionManager.getInstance().didComplete(this);
  123. }
  124. // private void processBitmapEntity(HttpEntity entity) throws IOException {
  125. // BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
  126. // Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
  127. // handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));
  128. // }
  129. private void sendMessage(String result) {
  130. Message message = Message.obtain(handler, DID_SUCCEED,
  131. listener);
  132. Bundle data = new Bundle();
  133. data.putString("callbackkey", result);
  134. message.setData(data);
  135. handler.sendMessage(message);
  136. }
  137. public static DefaultHttpClient getHttpClient() {
  138. HttpParams httpParams = new BasicHttpParams();
  139. HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
  140. HttpConnectionParams.setSoTimeout(httpParams, 20000);
  141. // HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
  142. DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
  143. return httpClient;
  144. }
  145. public static boolean isHttpSuccessExecuted(HttpResponse response) {
  146. int statusCode = response.getStatusLine().getStatusCode();
  147. return (statusCode > 199) && (statusCode < 400);
  148. }
  149. }

2 ConnectionManager類,將線程添加到隊列中

  1. package com.juupoo.common;
  2. import java.util.ArrayList;
  3. /**
  4. * Simple connection manager to throttle connections
  5. *
  6. * @author Greg Zavitz
  7. */
  8. public class ConnectionManager {
  9. public static final int MAX_CONNECTIONS = 5;
  10. private ArrayList<Runnable> active = new ArrayList<Runnable>();
  11. private ArrayList<Runnable> queue = new ArrayList<Runnable>();
  12. private static ConnectionManager instance;
  13. public static ConnectionManager getInstance() {
  14. if (instance == null)
  15. instance = new ConnectionManager();
  16. return instance;
  17. }
  18. public void push(Runnable runnable) {
  19. queue.add(runnable);
  20. if (active.size() < MAX_CONNECTIONS)
  21. startNext();
  22. }
  23. private void startNext() {
  24. if (!queue.isEmpty()) {
  25. Runnable next = queue.get(0);
  26. queue.remove(0);
  27. active.add(next);
  28. Thread thread = new Thread(next);
  29. thread.start();
  30. }
  31. }
  32. public void didComplete(Runnable runnable) {
  33. active.remove(runnable);
  34. startNext();
  35. }
  36. }
3 調用:
  1. new HttpConnection().post("user.login", args, callbackListener);
  2. private CallbackListener callbackListener = new HttpConnection.CallbackListener() {
  3. @Override
  4. public void callBack(String v) {
  5. if(v != "fail") {
  6. if("false".equals(v)) {
  7. LoginActivity.this.showInfo(R.string.username_or_pass_error);
  8. } else {
  9. // 登錄
  10. Intent intent = new Intent();
  11. intent.setClass(LoginActivity.this, MainActivity.class);
  12. LoginActivity.this.startActivity(intent);
  13. }
  14. } else {
  15. LoginActivity.this.showInfo(R.string.network_transfer_error);
  16. }
  17. progressDialog.dismiss();
  18. }
  19. };
Copyright © Linux教程網 All Rights Reserved