8.14
- AsyncTask,继承AsyncTask类,重写doInBackground(Params… params)方法,通过监听器和execute开启执行,异步任务AsyncTask的状态:onPreExecute(还未执行),doInBackground,onPostExecute
- Thread ,继承Thread类,重写run()方法,通过start()启动。
8.17
-
文件下载:DownloadManage的对象从系统服务Context.DOWNLOAD_SERVICE中获取:
mDownloadManage = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
使用过程:
-
构建下载请求:
下载请求就是DownloadManager的内部类Request
Uri uri = Uri.parse(imageUrlArray[arg2]); Request down = new Request(uri);//new一个Request对象 down.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI); down.setNotificationVisibility(Request.VISIBILITY_HIDDEN); down.setVisibleInDownloadsUi(false); down.setDestinationInExternalFilesDir(//设置下载文件在本地的保存路径 DownloadImageActivity.this, Environment.DIRECTORY_DCIM, arg2 + ".jpg");
-
进行下载操作:
mDownloadId = mDownloadManager.enqueue(down);//将下载请求加入任务队列中,等候下载
-
查询下载进度:
Query down_query = new Query(); down_query.setFilterById(mDownloadId);//根据编号过滤下载任务 Cursor cursor = mDownloadManager.query(down_query);//根据查询请求获取符合条件的结果集游标 for (;; cursor.moveToNext()) { int nameIdx = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME); int mediaTypeIdx = cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE); int totalSizeIdx = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES); int nowSizeIdx = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR); int statusIdx = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS); int progress = (int) (100 * cursor.getLong(nowSizeIdx) / cursor.getLong(totalSizeIdx)); ...... tv_image_result.setText(desc);
-
-
http接口调用HttpURLConnection
URL url = new URL(req_data.url); //创建指定网络地址的HTTP连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); setConnHeader(conn,"GET",req_data); conn.connect();//开始连接 //对输入流中的数据进行解压,得到原始的应答字符串 resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(), conn.getHeaderField("Content-Encoding"),req_data.charset); resp_data.cookie = conn.getHeaderField("Set-Cookie"); conn.disconnect();//断开连接
- 1.API接口为空 2.getMessage方法的调用过程? 3.下载下来格式问题,怎样安装
8.18
-
HTTP接口调用
-
HttpRequest getData方法,建立连接获取数据
/HTTP接口调用,get文本数据 public static HttpRespData getData(HttpReqData req_data) { HttpRespData resp_data = new HttpRespData(); try { URL url = new URL(req_data.url); //创建指定网络地址的HTTP连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); setConnHeader(conn,"GET",req_data); conn.connect();//开始连接 //对输入流中的数据进行解压,得到原始的应答字符串 resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(), conn.getHeaderField("Content-Encoding"),req_data.charset); resp_data.cookie = conn.getHeaderField("Set-Cookie"); conn.disconnect();//断开连接 } catch (Exception e) { Log.e(TAG,"-----e:"+ e.getMessage()); e.printStackTrace(); e.getMessage(); } Log.e(TAG,"-----获取apk信息----resp_data.content:"+ resp_data.content); return resp_data; }
-
StreamTool.getUnzipStream方法,将请求得到的数据转化为String类型
//将请求得到的数据转化为String类型 public static String getUnzipStream (InputStream is,String content_encoding,String chatset) { String resp_content = ""; GZIPInputStream gzin = null; if (content_encoding != null && content_encoding.equals("") != true) { if (content_encoding.indexOf("GZIP") >= 0) { try { gzin = new GZIPInputStream(is); }catch (IOException e) { e.printStackTrace(); } } } try { if (gzin == null) { resp_content = new String(readInputStream(is),chatset); }else { resp_content = new String (readInputStream(gzin),chatset); } }catch (Exception e) { Log.e("$$$$", "e:"+e.getLocalizedMessage()); e.printStackTrace(); } return resp_content; }
-
HttpRequest类继承AsyncTask,调用HttpRequest getData方法实现接口调用
public class HttpRequest extends AsyncTask<Location,Void,String> { private String TAG = "HTTPRequest"; private String appUrl = "http://192.168.210.37:8083/api/VersionUpdate/GetVersionMessage?appName=RBPlatform"; private String resp = ""; public HttpRequest() { super(); } @Override protected String doInBackground(Location... params) { HttpReqData req_data = new HttpReqData(appUrl); HttpRespData resp_data = HttpRequestUtil.getData(req_data); String version_Name = "未知"; return resp_data.content; } @Override protected void onPreExecute() { super.onPreExecute(); } //已经完成处理 @Override protected void onPostExecute(String s) { mListener.onFindMessage(s); } //设置监听器 private OnHttpRequestListener mListener; public void setOnHttpMessageListener(OnHttpRequestListener listener){ mListener = listener; } public static interface OnHttpRequestListener { public abstract void onFindMessage(String message); } }
-
Activity类中,调用监听器来实现接口调用,并且将AsyncTask返回的请求数据显示
public void getMessage() { HttpRequest httpRequest = new HttpRequest(); httpRequest.setOnHttpMessageListener(this); httpRequest.execute(); } //onPostExecute方法任务执行完成时触发,输入的参数是DoInBackground的输出参数 public void onFindMessage(String message) { tv_message.setText(message); }
-
-
在genymotion模拟器上下载内容和自带的模拟器下载的内容不一样。
-
OkHTTP:OkHttp
-
OkHTTP实现接口调用,完成get请求
-
OKHttpRequest类封装OkHTTP的异步get请求方法
public class OKHttpRequest { public static String message = ""; public static String TAG = "OkHttpResquest"; //异步get public static void async_run(String url) throws Exception { Log.e(TAG,"-----异步get请求-----"); final OkHttpClient async_client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); //异步请求,发起请求可以继续做其他事情 async_client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException throwable) { throwable.printStackTrace(); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } // Log.e(TAG,"-----异步get请求-----response.body().string():"+response.body().string());//response.body().string()只能执行一次 // System.out.println(response.body().string()); message = response.body().string(); Log.e(TAG,"-----异步get请求-----response.body().string():"+message); } }); }
-
在activity类中调用封装好的方法
private String url = "http://192.168.210.37:8083/api/VersionUpdate/GetVersionMessage?appName=RBPlatform"; try { OKHttpRequest.async_run(url); String message = OKHttpRequest.message; tv_message.setText(message); } catch (Exception e) { e.printStackTrace(); }
-
8.19
-
接口不能用static修饰符修饰,非静态对象需要实例化对象来调用
-
进度对话框,进度条。 json数据格式转换
-
进度对话框ProgressDialog
private ProgressDialog mDialog; // 进度对话框 private void progressDialog() { mDialog = ProgressDialog.show(this,"请稍候","正在努力加载"); mHandler.postDelayed(mCloseDialog,1500); } //关闭对话框的任务 private Runnable mCloseDialog = new Runnable() { @Override public void run() { if (mDialog.isShowing()) { mDialog.dismiss(); tv_message.setText("API接口内容:\n"+message+"\n加载完成"); } } }; //创建一个处理器对象 private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0) { mDialog.setProgress(msg.arg1); }else if (msg.what == 1) { post(mCloseDialog); } } };
8.20
-
API 接口获取到的是json对象,需要转换为json串再进行解析
//将获取的json对象转换为json串 private String transJson(String JSONmessage) { try { JSONArray mArray = new JSONArray(JSONmessage); for (int i = 0; i < mArray.length(); i++) { JSONObject mJsonObject = mArray.getJSONObject(i); Log.d(TAG, "======================="+mJsonObject); mes = mJsonObject.toString(); } } catch (JSONException e) { e.printStackTrace(); } return mes; } // 解析json格式字符串 private String parserJson(String message) { String result = ""; try { JSONObject obj = new JSONObject(message); String app_name = obj.getString("App_Name"); int version_code = obj.getInt("Version_Code"); String version_name = obj.getString("Version_Name"); String update_message = obj.getString("Update_Message"); String update_date = obj.getString("Update_Date"); String update_url = obj.getString("UpdateUrl"); int rn = obj.getInt("RN"); result = String.format("%sapp_name = %s\n",result,app_name); result = String.format("%sversion_code = %d\n",result,version_code); result = String.format("%sversion_name = %s\n",result,version_name); result = String.format("%supdate_message= %s\n",result,update_message); result = String.format("%supdate_date = %s\n",result,update_date); result = String.format("%supdate_url = %s\n",result,update_url); result = String.format("%srn = %s\n",result,rn); }catch (JSONException e) { e.printStackTrace(); } return result; }