1. 程式人生 > >通過okhttp3下載檔案實現APP版本更新

通過okhttp3下載檔案實現APP版本更新

概況

思路是這樣的,首先在伺服器上把已經簽名打包的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; } }
  • 另一個是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);
    }

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);
                }
            }
        });
    }
  • 下載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();
           // }
        });
    }

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);
            }
        });
    }
}

注意:在跳轉到安裝介面時,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>
  • 然後在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>
  • 文章所用Demo這裡下載