更新功能主代码

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();
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容