更新功能主代碼

UpdateActivity

1.定義

 private String versionName;
    private int versionCode;
    MyReceiver receiver = new MyReceiver();
    public static final String BROADCAST_ACTION =
            "com.example.android.threadsample.BROADCAST";
    public static final String EXTENDED_DATA_STATUS =
            "com.example.android.threadsample.STATUS";
    private LocalBroadcastManager mLocalBroadcastManager;
    //服務(wù)器中APK下載地址
    private String updateurl;
    private Context context;
    //自動(dòng)更新的實(shí)現(xiàn)類
    private UpdateServicelmpl UpdateService;

2.獲得版本號(hào)

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //獲得APP版本名稱和版本號(hào)
        versionName = DeviceInfoUtil.getAppVersionName(getApplicationContext());
        versionCode = DeviceInfoUtil.getAppVersionCode(getApplicationContext());
//        Log.i("測(cè)試:", "versionName:"+versionName+",versionCode:"+versionCode);

        //更新接口
        UpdateService = new UpdateServicelmpl(handler);
        UpdateVO updatevo = new UpdateVO();
        try {
            UpdateService.UpdateClient(updatevo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        regist();
    }

3.處理返回消息

 public final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            switch (msg.arg1) {
                case UPDATA_CLIENT:
                    //處理服務(wù)器返回的結(jié)果
                    handleUpdateClientResult(bundle);
                    break;
            }
        }
    };

4.處理接口返回結(jié)果

private void handleUpdateClientResult(Bundle bundle){
        String json = bundle.getString(FunctionListEnum.UpdateClient.toString());
        ObjectMapper objectMapper = new ObjectMapper();
        if (null != json && !"".equals(json)){
            try {
                UpdateVO updatevo = objectMapper.readValue(json,UpdateVO.class);
                if (null != updatevo){
                    int serverversioncode = updatevo.getServerVersionCode();
                    updateurl = updatevo.getUrl();
//                    if ( !"".equals(serverversioncode)){
                        if (versionCode <serverversioncode){
                            //對(duì)話框通知用戶升級(jí)程序
                            showUpdataDialog();
                        }else
                            //進(jìn)入程序主界面
                            LoginMain();
//                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            Toast.makeText(getApplicationContext(), "下載新版本失敗",  Toast.LENGTH_SHORT).show();
            LoginMain();
        }
    }

5.彈出對(duì)話框提示更新

/**
     * 彈出對(duì)話框通知用戶更新程序
     彈出對(duì)話框的步驟:
     1.創(chuàng)建alertDialog的builder.
     2.要給builder設(shè)置屬性, 對(duì)話框的內(nèi)容,樣式,按鈕
     3.通過builder 創(chuàng)建一個(gè)對(duì)話框
     4.對(duì)話框show()出來
     */
    protected void showUpdataDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("是否進(jìn)行版本升級(jí)?");
//        builer.setMessage(info.getDescription());.
        //當(dāng)點(diǎn)確定按鈕時(shí)從服務(wù)器上下載 新的apk 然后安裝
        builer.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i("提示","下載apk,更新");
                dialog.dismiss();
                downLoadApk();
            }
        });
        //當(dāng)點(diǎn)取消按鈕時(shí)進(jìn)行登錄
        builer.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                LoginMain();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }

6.從服務(wù)器中下載APK

/**
     * 從服務(wù)器中下載APK
     */
    private void downLoadApk(){

        if (TextUtils.isEmpty(updateurl)) {
            return;
        }

        try {
            String serviceString = Context.DOWNLOAD_SERVICE;
            context =  this.getApplicationContext();
            final DownloadManager downloadManager = (DownloadManager) context.getSystemService(serviceString);
            //將下載地址url放入uri中

//            //從資源文件獲取服務(wù)器 地址
//            String path = getResources().getString(R.string.serverurl);

            Uri uri = Uri.parse(updateurl);
            DownloadManager.Request request = new DownloadManager.Request(uri);
            request.allowScanningByMediaScanner();
            request.setVisibleInDownloadsUi(true);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setMimeType("application/vnd.android.package-archive");

            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/app-debug/","app-debug.apk");
            if (file.exists()){
                file.delete();
            }
            request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath()+"/app-debug/", "app-debug.apk");
//            File newfile = new File(String.valueOf(request));
            //獲得唯一下載id
            long refernece = downloadManager.enqueue(request);
            //將id放進(jìn)Intent
            Intent localIntent = new Intent(BROADCAST_ACTION);
            localIntent.putExtra(EXTENDED_DATA_STATUS,refernece);
            //查詢下載信息
            DownloadManager.Query query=new DownloadManager.Query();
            query.setFilterById(refernece);
            try{
                boolean isGoging=true;
                while(isGoging){
                    Cursor cursor = downloadManager.query(query);
                    if (cursor != null && cursor.moveToFirst()) {
                        int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                        switch(status){
                            case DownloadManager.STATUS_RUNNING:
                                Toast.makeText(getApplicationContext(), "下載中",  Toast.LENGTH_SHORT).show();
                                break;
                            //如果下載狀態(tài)為成功
                            case DownloadManager.STATUS_SUCCESSFUL:
                                isGoging=false;
                                installApkDialog();
                                //退出當(dāng)前程序
//                                android.os.Process.killProcess(android.os.Process.myPid());
//                                InstallAPK();
//                                //調(diào)用LocalBroadcastManager.sendBroadcast將intent傳遞回去
//                                mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
//                                mLocalBroadcastManager.sendBroadcast(localIntent);
                                break;
                            case DownloadManager.STATUS_FAILED:
                                isGoging = false;
                                Toast.makeText(getApplicationContext(), "下載新版本失敗",  Toast.LENGTH_SHORT).show();
                                LoginMain();
                                break;
                            case DownloadManager.STATUS_PAUSED:
                                searchReason();
                                break;
                        }
                    }

                    if(cursor!=null){
                        cursor.close();
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        } catch (Exception exception) {
            Toast.makeText(getApplicationContext(), "下載新版本失敗",  Toast.LENGTH_SHORT).show();
            LoginMain();
        }

    }

7.安裝新版本(未修改好,自動(dòng)安裝提示解析錯(cuò)誤,手動(dòng)安裝成功)

 protected void installApkDialog(){
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("退出安裝新版本");
//        builer.setMessage(info.getDescription());.
        //當(dāng)點(diǎn)確定按鈕時(shí)從服務(wù)器上下載 新的apk 然后安裝
        builer.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
        //當(dāng)點(diǎn)取消按鈕時(shí)進(jìn)行登錄
//        builer.setNegativeButton("否", new DialogInterface.OnClickListener() {
//            public void onClick(DialogInterface dialog, int which) {
//                // TODO Auto-generated method stub
//                //退出當(dāng)前程序
//                android.os.Process.killProcess(android.os.Process.myPid());
//            }
//        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }

8.下載暫停原因分析

 //下載暫停原因
    private void searchReason(){
        String serviceString = Context.DOWNLOAD_SERVICE;
        DownloadManager downloadManager;
        downloadManager = (DownloadManager)getSystemService(serviceString);

        // 為暫停的下載任務(wù)創(chuàng)建query
        DownloadManager.Query pausedDownloadQuery = new DownloadManager.Query();
        pausedDownloadQuery.setFilterByStatus(DownloadManager.STATUS_PAUSED);

        // Query the Download Manager for paused downloads.
        Cursor pausedDownloads = downloadManager.query(pausedDownloadQuery);

        // Find the column indexes for the data we require.
        int reasonIdx = pausedDownloads.getColumnIndex(DownloadManager.COLUMN_REASON);
        while (pausedDownloads.moveToNext()) {
            int reason = pausedDownloads.getInt(reasonIdx);
            switch (reason) {
                case DownloadManager.PAUSED_QUEUED_FOR_WIFI :
                    pausedDownloads.close();
                    showNoWifiDialog();
                    break;
                case DownloadManager.PAUSED_WAITING_FOR_NETWORK :
                    pausedDownloads.close();
                    showNoNetworkDialog();
                    break;
                case DownloadManager.PAUSED_WAITING_TO_RETRY :
                    // Close the result Cursor.
                    pausedDownloads.close();
                    showRetryDialog();
                    break;
                case DownloadManager.PAUSED_UNKNOWN:
                    // Close the result Cursor.
                    pausedDownloads.close();
                    showRetryDialog();
                    break;
            }

        }

    }
    //顯示由于移動(dòng)網(wǎng)絡(luò)數(shù)據(jù)問題,等待WiFi連接能用后再重新進(jìn)入下載隊(duì)列。
    protected void showNoWifiDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("移動(dòng)網(wǎng)絡(luò)數(shù)據(jù)有問題,需要等待wifi連接后才能下載");
//        builer.setMessage(info.getDescription());.
        //當(dāng)點(diǎn)確定按鈕時(shí)從服務(wù)器上下載 新的apk 然后安裝
        builer.setPositiveButton("重新下載", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i("提示","下載apk,更新");
                downLoadApk();
            }
        });
        //當(dāng)點(diǎn)取消按鈕時(shí)進(jìn)行登錄
        builer.setNegativeButton("取消下載", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                LoginMain();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }
    //可能由于沒有網(wǎng)絡(luò)連接而無法下載,等待有可用的網(wǎng)絡(luò)連接恢復(fù)。.
    protected void showNoNetworkDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("沒有網(wǎng)絡(luò)連接");
//        builer.setMessage(info.getDescription());.
        //當(dāng)點(diǎn)確定按鈕時(shí)從服務(wù)器上下載 新的apk 然后安裝
        builer.setPositiveButton("重試", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i("提示","下載apk,更新");
                downLoadApk();
            }
        });
        //當(dāng)點(diǎn)取消按鈕時(shí)進(jìn)行登錄
        builer.setNegativeButton("取消下載", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                LoginMain();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }
    //由于重重原因?qū)е孪螺d暫停,等待重試。
    protected void showRetryDialog(){
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("由于未知原因?qū)е孪螺d暫停,是否等待重試");
//        builer.setMessage(info.getDescription());.
        //當(dāng)點(diǎn)確定按鈕時(shí)從服務(wù)器上下載 新的apk 然后安裝
        builer.setPositiveButton("重試", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i("提示","下載apk,更新");
                downLoadApk();
            }
        });
        //當(dāng)點(diǎn)取消按鈕時(shí)進(jìn)行登錄
        builer.setNegativeButton("取消下載", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                LoginMain();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }

9.注冊(cè)廣播(未用到)

//注冊(cè)廣播
    private void regist() {

        IntentFilter intentFilter = new IntentFilter(UpdateActivity.BROADCAST_ACTION);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);
    }

    //接受到廣播,處理傳遞過來的數(shù)據(jù),下載完成,自動(dòng)安裝應(yīng)用
    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
                String data = intent.getStringExtra(UpdateActivity.EXTENDED_DATA_STATUS);
                Log.i("test", data);

            try {
                if(null!= data && !"".equals(data)){
                    long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                    Toast.makeText(UpdateActivity.this, "編號(hào):"+id+"的下載任務(wù)已經(jīng)完成!", Toast.LENGTH_SHORT).show();
                    intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/app-debug.apk")),
                            "application/vnd.android.package-archive");
                    startActivity(intent);
                }else{
                    Toast.makeText(getApplicationContext(), "下載新版本失敗",  Toast.LENGTH_SHORT).show();
                    showRetryDialog();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    //取消注冊(cè)廣播
    protected void onDestroy() {
        super.onDestroy();
//        cancel();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

10.安裝新版本

private void InstallAPK() {
    Intent intent = new Intent();
    //執(zhí)行動(dòng)作
    intent.setAction(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //執(zhí)行的數(shù)據(jù)類型
    intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/app-debug.apk")),
            "application/vnd.android.package-archive");
    startActivity(intent);
}

11.進(jìn)入主界面

/*
     * 進(jìn)入程序的主界面
     */
    private void LoginMain(){
        Intent intent = new Intent(this,ActivateBoxActivity.class);
        startActivity(intent);
        //結(jié)束掉當(dāng)前的activity
        this.finish();
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,030評(píng)論 25 709
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程,因...
    小菜c閱讀 7,329評(píng)論 0 17
  • 《裕語言》速成開發(fā)手冊(cè)3.0 官方用戶交流:iApp開發(fā)交流(1) 239547050iApp開發(fā)交流(2) 10...
    葉染柒丶閱讀 28,749評(píng)論 5 20
  • 半杯干紅下肚,一路打著太極一路慢跑,一個(gè)稚嫩的聲音傳入耳膜:“爸爸,我可以的,我可以的,給我給我······” 三...
    丹心隨行閱讀 750評(píng)論 0 0
  • 我熱愛閱讀,一直深入到骨子里。這其中不僅僅能吸取知識(shí)的養(yǎng)分,更多的時(shí)候他能讓我戒驕戒躁。我相信,我們這輩的年輕人更...
    暖遇閱讀 523評(píng)論 4 8

友情鏈接更多精彩內(nèi)容