基於xutils3的單檔案下載
阿新 • • 發佈:2019-01-03
開篇都不知道要叨叨啥,唉~,直接進入正題——>go!!
介面就是一個button,就不貼了。
MainActivity
package com.fun.downloaduploaddemo; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.File; public class MainActivity extends AppCompatActivity { private Button buttonDownloadFile; private DownLoadModel model = new DownLoadModel(); private static final String BASE_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator + "aqsc" + File.separator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonDownloadFile = (Button) findViewById(R.id.bt_downloadFile); if (model.fileIsExists(BASE_PATH + "在三國殺怪升級當戰神.txt")) { buttonDownloadFile.setText("檔案已經下載"); } buttonDownloadFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = "http://txt.bookben.com/c_down/2018/03/139675/在三國殺怪升級當戰神(書本網www.bookben.com).txt"; if (model.fileIsExists(BASE_PATH + "在三國殺怪升級當戰神.txt")) { Toast.makeText(MainActivity.this, "檔案已經存在,正在開啟檔案!", Toast.LENGTH_SHORT).show(); File file = new File(BASE_PATH + "在三國殺怪升級當戰神.txt"); model.openFile(MainActivity.this, file); } else { model = new DownLoadModel(MainActivity.this, url, "在三國殺怪升級當戰神.txt"); } } }); } @Override protected void onResume() { super.onResume(); if (model.fileIsExists(BASE_PATH + "在三國殺怪升級當戰神.txt")) { buttonDownloadFile.setText("檔案已經下載"); } else { buttonDownloadFile.setText("檔案下載"); } } @Override protected void onPause() { super.onPause(); buttonDownloadFile.setText("檔案已經下載"); } }
onResume方法中檢查在下載目錄中是否存在該檔案,存在更改button的text為已經下載,下載完成後直接開啟檔案,Activity進入onPause方法,重寫onPause方法更改button狀態。
DownLoadModel
package com.fun.downloaduploaddemo; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; import java.io.File; public class DownLoadModel { private Context context; private String url; private String fileName; private ProgressDialog progressDialog; private static final String BASE_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator + "aqsc" + File.separator; public DownLoadModel(Context context, String url, String fileName) { this.context = context; this.url = url; this.fileName = fileName; verifyStoragePermissions((Activity) context); String path = BASE_PATH + fileName; downloadFile(url, path); } public DownLoadModel() { } private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; /** * 檢查應用程式是否允許寫入儲存裝置 * 如果應用程式不允許那麼會提示使用者授予許可權 * * @param activity */ public static void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } } private void downloadFile(final String url, final String path) { progressDialog = new ProgressDialog(context); RequestParams requestParams = new RequestParams(url); requestParams.setSaveFilePath(path); x.http().get(requestParams, new Callback.ProgressCallback<File>() { @Override public void onWaiting() { } @Override public void onStarted() { } @Override public void onLoading(long total, long current, boolean isDownloading) { progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("親,努力下載中。。。"); progressDialog.show(); progressDialog.setMax((int) total); progressDialog.setProgress((int) current); } @Override public void onSuccess(File result) { Toast.makeText(context, "下載成功", Toast.LENGTH_SHORT).show(); Log.e("result", "result=" + result); progressDialog.dismiss(); openFile(context, result); } @Override public void onError(Throwable ex, boolean isOnCallback) { ex.printStackTrace(); Toast.makeText(context, "下載失敗,請檢查網路和SD卡", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); } /** * 根據檔案字尾名匹配MIMEType * * @param file * @return */ private static String getMIMEType(File file) { String type = "*/*"; String name = file.getName(); int index = name.lastIndexOf('.'); if (index < 0) { return type; } String end = name.substring(index, name.length()).toLowerCase(); if (TextUtils.isEmpty(end)) return type; for (int i = 0; i < MIME_MapTable.length; i++) { if (end.equals(MIME_MapTable[i][0])) type = MIME_MapTable[i][1]; } return type; } /** * 開啟檔案 * * @param context * @param file 檔案 */ public void openFile(Context context, File file) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(Intent.ACTION_VIEW); String type = getMIMEType(file); //設定intent的data和Type屬性。 intent.setDataAndType(Uri.fromFile(file), type); context.startActivity(intent); } /** * 自動安裝apk檔案 * * @param context * @param file */ public static void openApk(Context context, File file) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); context.startActivity(intent); } //判斷檔案是否存在 public boolean fileIsExists(String strFile) { try { File f = new File(strFile); if (!f.exists()) { return false; } } catch (Exception e) { return false; } return true; } private static final String[][] MIME_MapTable = { {".3gp", "video/3gpp"}, {".apk", "application/vnd.android.package-archive"}, {".asf", "video/x-ms-asf"}, {".avi", "video/x-msvideo"}, {".bin", "application/octet-stream"}, {".bmp", "image/bmp"}, {".c", "text/plain"}, {".class", "application/octet-stream"}, {".conf", "text/plain"}, {".cpp", "text/plain"}, {".doc", "application/msword"}, {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {".xls", "application/vnd.ms-excel"}, {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {".exe", "application/octet-stream"}, {".gif", "image/gif"}, {".gtar", "application/x-gtar"}, {".gz", "application/x-gzip"}, {".h", "text/plain"}, {".htm", "text/html"}, {".html", "text/html"}, {".jar", "application/java-archive"}, {".java", "text/plain"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".js", "application/x-javascript"}, {".log", "text/plain"}, {".m3u", "audio/x-mpegurl"}, {".m4a", "audio/mp4a-latm"}, {".m4b", "audio/mp4a-latm"}, {".m4p", "audio/mp4a-latm"}, {".m4u", "video/vnd.mpegurl"}, {".m4v", "video/x-m4v"}, {".mov", "video/quicktime"}, {".mp2", "audio/x-mpeg"}, {".mp3", "audio/x-mpeg"}, {".mp4", "video/mp4"}, {".mpc", "application/vnd.mpohun.certificate"}, {".mpe", "video/mpeg"}, {".mpeg", "video/mpeg"}, {".mpg", "video/mpeg"}, {".mpg4", "video/mp4"}, {".mpga", "audio/mpeg"}, {".msg", "application/vnd.ms-outlook"}, {".ogg", "audio/ogg"}, {".pdf", "application/pdf"}, {".png", "image/png"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppt", "application/vnd.ms-powerpoint"}, {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, {".prop", "text/plain"}, {".rc", "text/plain"}, {".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"}, {".sh", "text/plain"}, {".tar", "application/x-tar"}, {".tgz", "application/x-compressed"}, {".txt", "text/plain"}, {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"}, {".wmv", "audio/x-ms-wmv"}, {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"}, {".z", "application/x-compress"}, {".zip", "application/x-zip-compressed"}, {"", "*/*"} }; }
因為http post請求目標網站會出現 405 Not Allowed 的錯誤,原因為是Apache、IIS、Nginx等絕大多數web伺服器,都不允許靜態檔案響應POST請求,所以我用的是x.http().get(requestParams, new Callback.ProgressCallback<File>()),沒用x.http().post(requestParams, new Callback.ProgressCallback<File>())方法。
小白一枚有什麼問題請多多包涵,不過一定要告訴我,繼續寫bug!!!