版本更新

package com.example.update;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Xml;
/**
 *
 *  *  
 * Simple to Introduction  
 * @ProjectName:  [Update]
 * @Package:      [com.example.update.VersionUpdateUtils.java]  
 * @ClassName:    [VersionUpdateUtils]   
 * @Description:  [版本更新的工具类]   
 * @Author:       [Leanper]   
 * @CreateDate:   [2016-7-28 上午9:19:21]   
 * @UpdateUser:   [Leanper]   
 * @UpdateDate:   [2016-7-28 上午9:19:21]   
 * @UpdateRemark: [说明本次修改内容]  
 * @Version:      [v1.0]
 */
public class VersionUpdateUtils{

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String xml = (String) msg.obj;
            jiexiApkData(xml);
        }
    };

    private String apkUrl = "http://www.oschina.net/MobileAppVersion.xml";

    private Update update;

    private Context context;

    /**
     * 解析apk
     *
     * @param xml
     */
    public void jiexiApkData(String xml) {
        try {
            XmlPullParser newPullParser = Xml.newPullParser();
            ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
            newPullParser.setInput(bais, "utf-8");
            int eventType = newPullParser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String name = newPullParser.getName();
                switch (eventType) {
                case XmlPullParser.START_TAG:
                    if ("android".equals(name)) {
                        update = new Update();
                    } else if ("versionCode".equals(name)) {
                        update.setVersionCode(newPullParser.nextText());
                    } else if ("versionName".equals(name)) {
                        update.setVersionName(newPullParser.nextText());
                    } else if ("downloadUrl".equals(name)) {
                        update.setDownloadUrl(newPullParser.nextText());
                    } else if ("updateLog".equals(name)) {
                        update.setUpdateLog(newPullParser.nextText());
                    }
                    break;
                }
                eventType = newPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 判断更新
        panduanUpdate();
    }

    /**
     * 请求apk信息
     */
    public void reguestAPKData(Context context) {
        this.context=context;
        new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(apkUrl);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setConnectTimeout(5000);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    InputStream is = conn.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = is.read(buffer)) != -1) {
                        baos.write(buffer, 0, len);
                    }
                    Message message = handler.obtainMessage();
                    message.obj = baos.toString();
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 安装apk
     */

    protected void installApk(File file) {

        Intent intent = new Intent();

        // 执行动作

        intent.setAction(Intent.ACTION_VIEW);

        // 执行的数据类型

        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");

        context.startActivity(intent);

    }

    protected void downLoadApk() {

        final ProgressDialog pd; // 进度条对话框

        pd = new ProgressDialog(context);

        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        pd.setMessage("正在下载更新");

        pd.show();
        // 进行下载操作
        new Thread() {

            @Override
            public void run() {

                try {
                    // 下载
                    File file = DownLoadManager.getFileFromServer(
                            update.getDownloadUrl(), pd);

                    sleep(3000);
                    // 安装
                    installApk(file);

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

                } catch (Exception e) {

                }

            }
        }.start();
    }

    /**
     * 提醒更新的对话框
     */
    private void initAlert() {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("软件版本更新");
            builder.setMessage(update.getUpdateLog());
            builder.setPositiveButton("立即更新",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 点击立即下载更新包
                            downLoadApk();
                        }
                    });
            builder.setNegativeButton("以后再说",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得本应用的版本信息
     */
    private void panduanUpdate() {
        try {
            PackageManager packageManager = App.getContext()
                    .getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(App
                    .getContext().getPackageName(), 0);
            String versionName = packInfo.versionName;
            if (!versionName.equals(update.getVersionName())) {
                initAlert();
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

}



package com.example.update;

import android.app.ProgressDialog;
import android.os.Environment;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载管理
 *
 */
public class DownLoadManager {
    public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{

        //濡傛灉鐩哥瓑鐨勮瘽琛ㄧず褰撳墠鐨剆dcard鎸傝浇鍦ㄦ墜鏈轰笂骞朵笖鏄彲鐢ㄧ殑

        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;

        }

    }
}




package com.example.update;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.lidroid.xutils.HttpUtils;

public class MainActivity extends Activity {

    private String apkUrl = "http://www.oschina.net/MobileAppVersion.xml";
    private TextView lv;
    private Button btn_newapk;
    private Update update;
    private HttpUtils utils;
    private VersionUpdateUtils vutils;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String xml = (String) msg.obj;
         vutils.jiexiApkData(xml);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //找控件
        initView();
        //注册监听
        setOnClicklistener();
        
    }

    private void setOnClicklistener() {
        
        //为检查更新的按钮注册监听
        btn_newapk.setOnClickListener(new View.OnClickListener() {
          

            @Override
            public void onClick(View v) {
                vutils = new VersionUpdateUtils();
                vutils.reguestAPKData(MainActivity.this);
            }
        });
    }


    /**
     * 找控件
     */
    private void initView() {
        lv = (TextView) findViewById(R.id.lv);
        btn_newapk = (Button) findViewById(R.id.btn_newapk);
    }
}

//在applicationl=里设置上下文


public class App extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        context = this.getApplicationContext();
    }
    public static Context getContext(){
        return context;
        
    }


//更新的实体类

public class Update {
    private String versionCode;

    private String versionName;

    private String downloadUrl;

    private String updateLog;

    public String getVersionCode() {
        return versionCode;
    }

    public void setVersionCode(String versionCode) {
        this.versionCode = versionCode;
    }

    public String getVersionName() {
        return versionName;
    }

    public void setVersionName(String versionName) {
        this.versionName = versionName;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public void setDownloadUrl(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }

    public String getUpdateLog() {
        return updateLog;
    }

    public void setUpdateLog(String updateLog) {
        this.updateLog = updateLog;
    }
}


最后需要添加权限

 <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值