更新功能主代码

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;
    //服务器中APK下载地址
    private String updateurl;
    private Context context;
    //自动更新的实现类
    private UpdateServicelmpl UpdateService;

2.获得版本号

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

        //获得APP版本名称和版本号
        versionName = DeviceInfoUtil.getAppVersionName(getApplicationContext());
        versionCode = DeviceInfoUtil.getAppVersionCode(getApplicationContext());
//        Log.i("测试:", "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:
                    //处理服务器返回的结果
                    handleUpdateClientResult(bundle);
                    break;
            }
        }
    };

4.处理接口返回结果

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){
                            //对话框通知用户升级程序
                            showUpdataDialog();
                        }else
                            //进入程序主界面
                            LoginMain();
//                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            Toast.makeText(getApplicationContext(), "下载新版本失败",  Toast.LENGTH_SHORT).show();
            LoginMain();
        }
    }

5.弹出对话框提示更新

/**
     * 弹出对话框通知用户更新程序
     弹出对话框的步骤:
     1.创建alertDialog的builder.
     2.要给builder设置属性, 对话框的内容,样式,按钮
     3.通过builder 创建一个对话框
     4.对话框show()出来
     */
    protected void showUpdataDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("是否进行版本升级?");
//        builer.setMessage(info.getDescription());.
        //当点确定按钮时从服务器上下载 新的apk 然后安装
        builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i("提示","下载apk,更新");
                dialog.dismiss();
                downLoadApk();
            }
        });
        //当点取消按钮时进行登录
        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.从服务器中下载APK

/**
     * 从服务器中下载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中

//            //从资源文件获取服务器 地址
//            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放进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;
                            //如果下载状态为成功
                            case DownloadManager.STATUS_SUCCESSFUL:
                                isGoging=false;
                                installApkDialog();
                                //退出当前程序
//                                android.os.Process.killProcess(android.os.Process.myPid());
//                                InstallAPK();
//                                //调用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.安装新版本(未修改好,自动安装提示解析错误,手动安装成功)

 protected void installApkDialog(){
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("退出安装新版本");
//        builer.setMessage(info.getDescription());.
        //当点确定按钮时从服务器上下载 新的apk 然后安装
        builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
        //当点取消按钮时进行登录
//        builer.setNegativeButton("否", new DialogInterface.OnClickListener() {
//            public void onClick(DialogInterface dialog, int which) {
//                // TODO Auto-generated method stub
//                //退出当前程序
//                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);

        // 为暂停的下载任务创建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;
            }

        }

    }
    //显示由于移动网络数据问题,等待WiFi连接能用后再重新进入下载队列。
    protected void showNoWifiDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("移动网络数据有问题,需要等待wifi连接后才能下载");
//        builer.setMessage(info.getDescription());.
        //当点确定按钮时从服务器上下载 新的apk 然后安装
        builer.setPositiveButton("重新下载", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i("提示","下载apk,更新");
                downLoadApk();
            }
        });
        //当点取消按钮时进行登录
        builer.setNegativeButton("取消下载", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                LoginMain();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }
    //可能由于没有网络连接而无法下载,等待有可用的网络连接恢复。.
    protected void showNoNetworkDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("没有网络连接");
//        builer.setMessage(info.getDescription());.
        //当点确定按钮时从服务器上下载 新的apk 然后安装
        builer.setPositiveButton("重试", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i("提示","下载apk,更新");
                downLoadApk();
            }
        });
        //当点取消按钮时进行登录
        builer.setNegativeButton("取消下载", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                LoginMain();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }
    //由于重重原因导致下载暂停,等待重试。
    protected void showRetryDialog(){
        AlertDialog.Builder builer = new AlertDialog.Builder(this);
        builer.setTitle("由于未知原因导致下载暂停,是否等待重试");
//        builer.setMessage(info.getDescription());.
        //当点确定按钮时从服务器上下载 新的apk 然后安装
        builer.setPositiveButton("重试", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i("提示","下载apk,更新");
                downLoadApk();
            }
        });
        //当点取消按钮时进行登录
        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.注册广播(未用到)

//注册广播
    private void regist() {

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

    //接受到广播,处理传递过来的数据,下载完成,自动安装应用
    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, "编号:"+id+"的下载任务已经完成!", 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();
            }
        }
    }
    //取消注册广播
    protected void onDestroy() {
        super.onDestroy();
//        cancel();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

10.安装新版本

private void InstallAPK() {
    Intent intent = new Intent();
    //执行动作
    intent.setAction(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);
}

11.进入主界面

/*
     * 进入程序的主界面
     */
    private void LoginMain(){
        Intent intent = new Intent(this,ActivateBoxActivity.class);
        startActivity(intent);
        //结束掉当前的activity
        this.finish();
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容