Android版本更新

来源:互联网 发布:java发送邮件的代码 编辑:程序博客网 时间:2024/04/30 08:57

必须添加获取网络权限和读写的权限

private String path="http://www.oschina.net/MobileAppVersion.xml";
    private Handler handler=new Handler(){
        private  String xml;

        public void handleMessage(Message msg) {
            
            switch (msg.what) {
            case 0:
                xml=(String) msg.obj;
                xml(xml);
                break;
            case 1:
                downLoadApk();
                break;
            default:
                break;
            }
        }

    };
    private Shengji sj;
    private AlertDialog dialog;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //得到数据
        HttpUtils httpUtils=new HttpUtils();
        httpUtils.send(HttpMethod.GET, path, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                Message msg=Message.obtain();
                msg.obj=arg0.result;
                msg.what=0;
                handler.sendMessage(msg);
            }

        });
      
    }
    
    public void jiance(View v){
        try {
            int versionCode = MainActivity.this.getPackageManager()
                    .getPackageInfo(MainActivity.this.getPackageName(),
                            0).versionCode;
            
            if(sj.versionCode<=versionCode){
                Log.i("aaa", "无需升级");
            }else{
                dialog = new AlertDialog.Builder(MainActivity.this).setTitle("有新版本!!!")
                        .setIcon(R.drawable.ic_launcher).setMessage(sj.updateLog)
                        .setPositiveButton("立刻升级", onclick)
                        .setNegativeButton("暂不升级", null).create();
                dialog.show();
            }
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    DialogInterface.OnClickListener onclick = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            handler.sendEmptyMessage(1);
        }

    };
    // 下载apk
            private void downLoadApk() {
                // TODO Auto-generated method stub

                final ProgressDialog pd; // 进度条对话框
                pd = new ProgressDialog(this);
                pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pd.setMessage("正在下载更新");
                pd.show();

                new Thread() {
                    @Override
                    public void run() {
                        try {
                            File file = getFileFromServer(sj.downloadUrl, pd);
                            sleep(3000);

                            // 安装APk
                            Intent intent = new Intent();
                            // 执行动作
                            intent.setAction(Intent.ACTION_VIEW);
                            // 执行的数据类型
                            intent.setDataAndType(Uri.fromFile(file),
                                    "application/vnd.android.package-archive");
                            startActivity(intent);

                            pd.dismiss(); // 结束掉进度条对话框

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();

            };
            public File getFileFromServer(String path, ProgressDialog pd)
                    throws Exception {
                // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    // 获取到文件的大小
                    pd.setMax(conn.getContentLength());
                    InputStream is = conn.getInputStream();
                    File file = new File(Environment.getExternalStorageDirectory(),
                            "updata.apk");
                    FileOutputStream fos = new FileOutputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(is);
                    byte[] buffer = new byte[1024];
                    int len;
                    int total = 0;
                    while ((len = bis.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        total += len;
                        // 获取当前下载量
                        pd.setProgress(total);
                    }
                    fos.close();
                    bis.close();
                    is.close();
                    return file;
                } else {
                    return null;
                }
            }
    private void xml(String xml) {
        XmlPullParser newPullParser = Xml.newPullParser();
        
        InputStream is=new ByteArrayInputStream(xml.getBytes());
        try {
            newPullParser.setInput(new InputStreamReader(is));
            
            int type = newPullParser.getEventType();
            
            while(type!=XmlPullParser.END_DOCUMENT){
                switch (type) {
                case XmlPullParser.START_DOCUMENT:
                    System.out.println("文档开始");
                    
                    break;
                case XmlPullParser.START_TAG:
                    
                    String name = newPullParser.getName();
                    
                    if(name.equals("android")){
                        sj= new Shengji();
                    }else if(name.equals("versionCode")){
                        String next=newPullParser.nextText();
//                        System.out.println("-------"+next);
                        sj.versionCode=Integer.parseInt(next);
                    }else if(name.equals("versionName")){
                        String next=newPullParser.nextText();
//                        System.out.println("-------"+next);
                        sj.versionName=next;
                    }else if(name.equals("downloadUrl")){
                        String next=newPullParser.nextText();
//                        System.out.println("-------"+next);
                        sj.downloadUrl=next;
                    }else if(name.equals("updateLog")){
                        String next=newPullParser.nextText();
//                        System.out.println("-------"+next);
                        sj.updateLog=next;
                    }
                    break;
                case XmlPullParser.END_TAG:
                    name=newPullParser.getName();
                    if(name.equals("android")){
                        
                    }
                    
                    break;
                }
                type=newPullParser.next();
                
            };
            
            
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    };


0 0
原创粉丝点击