通過okhttp3下載文件實現APP版本更新


原文:https://blog.csdn.net/qq_34261214/article/details/77124729

概況

思路是這樣的,首先在服務器上把已經簽名打包的apk放上去,還有一份TXT文件,文件上寫着相關的版本號,然后客戶端通過對比版本號決定是否下載文件。下載后就打開安裝界面安裝。 
這里寫圖片描述

第一步

把已經簽名打包apk和txt文件放上到服務器上,版本號要和txt文件上的描述一致。Android Studio的版本號除了在manifests上,寫上code和name(code是面向開發者,name就是用戶所看到的版本號),那么我要更新的是2.0版本,那么我應該寫2.0,並且要把訪問網絡和寫入數據權限寫上 
這里寫圖片描述
還要在build.gradle(Module:app)上更改版本號,如果是用eclipse開發就不需要這一步 
這里寫圖片描述
這里寫圖片描述
TXT文件的內容如下,第一行是版本號,第二行版本描述,第三行是apk的下載鏈接 
這里寫圖片描述

第二步

服務器端已經完成,接下來是代碼的實現。 
我這里采用okhttp3+mvp模式實現下載文件,如果有對這種模式不清楚的可以看在MVP模式下使用OkHttp3初試OkHttp3實現登錄功能

  • Model層有更新版本描述實例UpdateInfo和Okhttp3的get和post方法

  • 首先在Presenter上有查詢版本號和下載apk這兩個方法,這兩個都是使用Get請求

  • 在View上就需要有一個對應一個觸發更新的按鈕,顯示最新版本的Toast,顯示並詢問是否更新的Dialog,和顯示進度的ProgressDialog,一個跳轉到安裝界面的操作

Model層

  • 首先要有updateInfo,一個版本信息的實例
public class UpdateInfo { private String version; private String description; private String url; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 另一個是Modle,包裝着okhttp3的post和get方法,這里只需要get請求

    /** * get請求 * @param address * @param callback */ public void get(String address, okhttp3.Callback callback) { OkHttpClient client = new OkHttpClient(); FormBody.Builder builder = new FormBody.Builder(); FormBody body = builder.build(); Request request = new Request.Builder() .url(address) .build(); client.newCall(request).enqueue(callback); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Presenter層

  • 檢查是否需要更新
 public void updateAPK() {
        model = Model.getInstance(); model.get("TXT文件的url",new okhttp3.Callback(){ @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String responseBody = response.body().string(); StringBuffer sb = new StringBuffer(); BufferedReader reader = null; UpdateInfo updateInfo = new UpdateInfo(); Log.d("版本", "onResponse: "+responseBody); reader = new BufferedReader(new StringReader(responseBody)); updateInfo.setVersion(reader.readLine());//把版本信息讀出來 updateInfo.setDescription(reader.readLine()); updateInfo.setUrl(reader.readLine()); String new_version = updateInfo.getVersion(); Log.d("版本", "onResponse: "+updateInfo.getVersion()); Log.d("版本描述", "onResponse: "+updateInfo.getDescription()); Log.d("更新鏈接", "onResponse: "+updateInfo.getUrl()); String now_version = ""; try { PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),0); now_version = packageInfo.versionName;//獲取原版本號 } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if(new_version.equals(now_version)){ view.showError(""); Log.d("版本號是", "onResponse: "+now_version); }else{ view.showUpdateDialog(updateInfo); } } }); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 下載apk
    public void downFile(final String url) { Log.d("SettingPresenter", "downFile: "); model = Model.getInstance(); model.get(url,new okhttp3.Callback(){ @Override public void onFailure(Call call, IOException e) { view.downFial(); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null;//輸入流 FileOutputStream fos = null;//輸出流 try { is = response.body().byteStream();//獲取輸入流 long total = response.body().contentLength();//獲取文件大小 view.setMax(total);//為progressDialog設置大小 if(is != null){ Log.d("SettingPresenter", "onResponse: 不為空"); File file = new File(Environment.getExternalStorageDirectory(),"Earn.apk");// 設置路徑 fos = new FileOutputStream(file); byte[] buf = new byte[1024]; int ch = -1; int process = 0; while ((ch = is.read(buf)) != -1) { fos.write(buf, 0, ch); process += ch; view.downLoading(process); //這里就是關鍵的實時更新進度了! } } fos.flush(); // 下載完成 if(fos != null){ fos.close(); } view.downSuccess(); } catch (Exception e) { view.downFial(); Log.d("SettingPresenter",e.toString()); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } //private void down() { // progressDialog.cancel(); // } }); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

View層

這一層注意的東西很多,例如Android6.0以上等需要在這里設置一下權限,還有Dialog注意關閉,否則出現窗口泄露問題。話不多說,直接上代碼

public class MainActivity extends AppCompatActivity { //下載進度 private ProgressDialog progressDialog; private Button button; private SettingPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); presenter = new SettingPresenter(this,this); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Build.VERSION.SDK_INT >= 23) {//如果是6.0以上的 int REQUEST_CODE_CONTACT = 101; String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; //驗證是否許可權限 for (String str : permissions) { if (MainActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) { //申請權限 MainActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT); return; } } } presenter.updateAPK(); } }); } //顯示更新錯誤 public void showError(final String msg) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); } //顯示進度條 public void showUpdateDialog(final UpdateInfo updateInfo) { runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle("請升級APP至版本" + updateInfo.getVersion()); builder.setMessage(updateInfo.getDescription()); builder.setCancelable(false); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { downFile(updateInfo.getUrl()); } else { Toast.makeText(MainActivity.this,"SD卡不可用,請插入SD卡",Toast.LENGTH_LONG).show(); } } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); } }); } //下載apk操作 public void downFile(final String url) { progressDialog = new ProgressDialog(MainActivity.this); //進度條,在下載的時候實時更新進度,提高用戶友好度 progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setTitle("正在下載"); progressDialog.setMessage("請稍候..."); progressDialog.setProgress(0); progressDialog.show(); presenter.downFile(url); Log.d("SettingActivity", "downFile: "); } /** * 進度條實時更新 * @param i */ public void downLoading(final int i) { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.setProgress(i); } }); } /** * 下載成功 */ public void downSuccess() { runOnUiThread(new Runnable() { @Override public void run() { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle("下載完成"); builder.setMessage("是否安裝"); builder.setCancelable(false); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //aandroid N的權限問題 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile(MainActivity.this, "對應的包名.fileprovider", new File(Environment.getExternalStorageDirectory(), "軟件名.apk"));//注意修改 intent.setDataAndType(contentUri, "application/vnd.android.package-archive"); } else { intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "軟件名.apk")), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } startActivity(intent); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); } }); } /** * 下載失敗 */ public void downFial() { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.cancel(); Toast.makeText(MainActivity.this,"更新失敗",Toast.LENGTH_LONG).show(); } }); } public void setMax(final long total) { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.setMax((int) total); } }); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174

注意:在跳轉到安裝界面時,android 6.0即android N以上的需要設置權限。

  • 首先在Manifests加上
  <provider android:name="android.support.v4.content.FileProvider" android:authorities="對應的包名.fileprovider" android:grantUriPermissions="true" android:exported="false" > <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 然后在res中創建xml包,存放file_paths.xml文件
<?xml version="1.0" encoding="utf-8"?> <paths> <external-path path="Android/data/com.earn/" name="files_root" /> <external-path path="." name="external_storage_root" /> </paths>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 文章所用Demo這里下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM