Android客戶端apk自動檢測更新自動下載自動安裝的實現方法

王世暉發表於2016-03-14

改進了一個可以檢測版本更新自動下載自動安裝的客戶端升級方案。

在下載之前刪除之前的歷史下載檔案,減少垃圾資料。

先給出核心類

public class DownloadService extends Service {
    private DownloadManager mDownloadManager;
    private long enqueue;
    private BroadcastReceiver receiver;
    private  static final String APK_URL= IPAddress.DEFAULT_IP+"/portrait/app-youni.apk";
//    private  static final String APK_NAME="youni.apk";
    private  static final String APK_NAME="youni_"+ System.currentTimeMillis()+"_.apk";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        DebugLog.v("onBind");
        return null;
    }
    @Override
    public void onCreate() {
        DebugLog.v("onCreate");
        super.onCreate();
        /*刪除以前下載的安裝包*/
        RecursionDeleteFile(new File(Environment.getExternalStorageDirectory() + "/download/youni/"));
    }

    @Override
    public void onStart(Intent intent, int startId) {
        DebugLog.v("onStart");
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        DebugLog.v("onStartCommand");
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/youni/"+APK_NAME)),
                        "application/vnd.android.package-archive");
                startActivity(intent);
                stopSelf();
            }
        };
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        startDownload();
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        DebugLog.v("onDestroy");
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    private void startDownload() {
        mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(APK_URL));
        request.setDescription("正在為您下載 友你 App的最新版本");
        request.setMimeType("application/vnd.android.package-archive");
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS+"/youni", APK_NAME);
        enqueue = mDownloadManager.enqueue(request);
    }
    /**
     * 遞迴刪除檔案和資料夾
     * @param file    要刪除的根目錄
     */
    public void RecursionDeleteFile(File file){
        if(file.isFile()){
            file.delete();
            return;
        }
        if(file.isDirectory()){
            File[] childFile = file.listFiles();
            if(childFile == null || childFile.length == 0){
                file.delete();
                return;
            }
            for(File f : childFile){
                RecursionDeleteFile(f);
            }
            file.delete();
        }
    }
}
然後再檢測到伺服器有新版本後,彈出對話方塊,詢問使用者是否下載

  /*系統提示對話方塊*/
new AlertDialog.Builder(NewMainActivity.this).setTitle("操作提示")//設定對話方塊標題
        .setMessage("檢測到最新版本,是否要升級?")//設定顯示的內容
        .setPositiveButton("後臺下載",new DialogInterface.OnClickListener() {//新增確定按鈕
            @Override
            public void onClick(DialogInterface dialog, int which) {//確定按鈕的響應事件
                startService(new Intent(getApplicationContext(), DownloadService.class));
            }
        }).setNegativeButton("下次再說",new DialogInterface.OnClickListener() {//新增返回按鈕
    @Override
    public void onClick(DialogInterface dialog, int which) {//響應事件

    }
}).show();//在按鍵響應事件中顯示此對話方塊
下載後就可以自動安裝了


相關文章