編輯:關於android開發
AsyncHttpClient開源框架android-async-http還是很方便的。 AsyncHttpClient該類通常用在android應用程序中創建異步GET,
POST, PUT和DELETE HTTP請求,請求參數通過RequestParams實例創建,響應通過重寫匿名內部類 ResponseHandlerInterface的
方法處理。
public void uploadFile(ArrayListsendFilesPath) { if (sendFilesPath.size() == 0) return ; String strUploadFile = mstrIP + mstrUploadFile; AsyncHttpClient client = new AsyncHttpClient(); client.setURLEncodingEnabled(false); RequestParams params = new RequestParams(); params.put("user_name", mstrUser); params.put("token", mstrCheckPass); params.put("dir_parent", "@sys"); //批量上傳 for (int i = 0; i < sendFilesPath.size(); i++) { File myFile = new File(sendFilesPath.get(i)); try { params.put(myFile.getName(), myFile); } catch (FileNotFoundException e1) { continue; } } client.setTimeout(10000); client.post(strUploadFile, params, new AsyncHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable arg3) { Log.i("Show", "upload failed"); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String responseData = new String(); responseData = new String(responseBody); try { JSONObject jsonObject = new JSONObject(responseData); int status = jsonObject.getInt("status"); if (status == 1) { Log.i("Show", "upload 1"); } } catch (Exception e) { } } @Override public void onProgress(int bytesWritten, int totalSize) { super.onProgress(bytesWritten, totalSize); int count = (int) ((bytesWritten * 1.0 / totalSize) * 100); // 上傳進度顯示 progress.setProgress(count); Log.e("上傳 Progress>>>>>", bytesWritten + " / " + totalSize); } @Override public void onRetry(int retryNo) { super.onRetry(retryNo); // 返回重試次數 } }); }
public void deleteFile(final ArrayListneedDeleteFilesPath) { if (needDeleteFilesPath.size() == 0) return; String strDeleteFile = mstrIP + mstrDeleteFiles; AsyncHttpClient client = new AsyncHttpClient(); client.setURLEncodingEnabled(false); RequestParams params = new RequestParams(); params.put("user_name", mstrUser); params.put("token", mstrCheckPass); params.put("dir_parent", "@sys"); // 批量 for (int i = 0; i < needDeleteFilesPath.size(); i++) { params.put("files_id", needDeleteFilesPath.get(i)); client.setTimeout(10000); client.post(strDeleteFile, params, new AsyncHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable arg3) { Log.i("Show", "delete faile"); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String responseData = new String(responseBody); } }); } }
AsyncTask
TaskDownFile mDownFile = new TaskDownFile(); mDownFile.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, url_downFile,fileName, String.valueOf(nDownID));
public class TaskDownFile extends AsyncTask{ @Override protected void onPreExecute() { } @Override protected Boolean doInBackground(String... arg0) { String mFilePath; String urlString = arg0[0]; String fileName = arg0[1]; int nDownID = Integer.parseInt(arg0[2]); HttpURLConnection conn; if (mFileInfos == null || mFileInfos.size() <= 0) return false; try { File file = new File(mstrFilePath); if (!file.exists()) file.mkdir(); mFilePath = mstrFilePath + "/" + fileName; // 判斷當前安裝包路徑下面是否有已經下載的文件, 如有則不下載,只需要MD5校驗即可 String checkApkFilePath = mstrFilePath + "/" + fileName; File checkApkFile = new File(checkApkFilePath); if (checkApkFile.exists()) { // MD5校驗 String md5 = md5sum(mFilePath); String fileTime = getFileDataTime(checkApkFile); // MD5校驗是否文件相同,在根據時間判斷 if (md5.compareToIgnoreCase(mFileInfos.get(nDownID).md5) == 0) return true; else if (compareDataTime(fileTime, mFileInfos.get(nDownID).create_time) > 0) { mNumberList.add(nDownID); return true; } else { // 服務器文件最新, 刪除本地文件 checkApkFile.delete(); } } // 臨時安裝文件檢驗, 是否續傳文件 mFilePath = mFilePath + ".temp"; long haveDownLength = 0; File tempFile = new File(mFilePath); if (tempFile.exists()) haveDownLength = tempFile.length(); conn = (HttpURLConnection) new URL(urlString).openConnection(); if (haveDownLength != 0) conn.setRequestProperty("Connection", "Keep-Alive"); conn.setReadTimeout(6000); conn.setConnectTimeout(3000); conn.setChunkedStreamingMode(0); conn.setRequestMethod("GET"); conn.connect(); int fileSize = conn.getContentLength(); long countRead = haveDownLength; if (fileSize > 0) { InputStream stream = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(mFilePath, haveDownLength > 0 ? true : false); int read = 0; fileSize += haveDownLength; byte buffer[] = new byte[1024]; while ((read = stream.read(buffer)) >= 0) { countRead += read; fos.write(buffer, 0, (int) read); publishProgress((int) countRead, fileSize); } fos.flush(); stream.close(); fos.close(); } else { fileSize = (int) haveDownLength; } conn.disconnect(); if (countRead != fileSize) return false; int index = mFilePath.indexOf(".temp"); if (index >= 1) { String tempFilePath = mFilePath.substring(0, index); File renameFile = new File(mFilePath); File toFile = new File(tempFilePath); renameFile.renameTo(toFile); mFilePath = tempFilePath; return true; } } catch (IOException e) { Log.i("Show", e.toString()); return false; } finally { } return false; } @Override protected void onPostExecute(Boolean isSuccess) { //下載後干什麼 } @Override protected void onProgressUpdate(Integer...values) { //進度條 if (values[0] == null) return; downSize = values[0]; fileSize = values[1]; progress = (int) ((values[0] * 1.0 / values[1]) * 10000); mHandler.sendEmptyMessage(DOWNLOAD); } }
//文件md5獲取 public static String md5sum(String filename) { InputStream fis; byte[] buffer = new byte[1024]; int numRead = 0; MessageDigest md5; try { fis = new FileInputStream(filename); md5 = MessageDigest.getInstance("MD5"); while ((numRead = fis.read(buffer)) > 0) { md5.update(buffer, 0, numRead); } fis.close(); return toHexString(md5.digest()); } catch (Exception e) { System.out.println("error"); return null; } } //十六進制轉換成字符串 public static String toHexString(byte[] b) { char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; StringBuilder sb = new StringBuilder(b.length * 2); for (int i = 0; i < b.length; i++) { sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]); sb.append(HEX_DIGITS[b[i] & 0x0f]); } return sb.toString(); }
下載推薦使用HttpURLConnection,因為文件大的話,可以暫停下載,或者下載時候斷了,可以重新接著下載。
MD5在文件下載檢驗也是很重要,看文件有沒有丟失或者缺損。
下一章准備總結一下緩存txt數據,文件最後修改時間的比較,兩個string數據的比較。
Intent(一.顯示使用intent),顯示使用intent 大家都知道如果手機只有一個活動的應用,那這個應用也太簡單了吧。如同網頁一下,是有多
14條Android Studio常用的的配置 14條Android Studio常用的的配置 1,修改idea.properties文件 找到\bin\idea.pro
Android中自定義視圖View之---進階篇(Canvas的使用) 一、前言 那麼今天,我們繼續來看一篇關於Android中的UI篇,如何自定義視圖View的進階篇,
Android SurfaceView的生命周期,androidsurfaceview本文利用SurfaceView來實現視頻的播放 本文地址:http://www.cn