Android手机从服务器更新软件到手机本地

package com.altersoft.FoodMisClient;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class Update extends Activity {

    public static float localVersion = 0;
    public static float serverVersion = 0;
    public ProgressDialog pBar;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.contact_manager);

        initGlobal();// 初始化本地版本和服务器版本
        checkVersion();// 检查本地版本是否需要更新
    }

    public void initGlobal() {
        try {
            localVersion = getPackageManager().getPackageInfo(getPackageName(),
                    0).versionCode; // 设置本地版本号
            serverVersion = 0;
            version("http://60.171.56.198:8000/Home/Version");// 下载版本号信息
            ReadXML();// 从下载文件中读取版本号并给版本号变量赋值
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void version(final String url) {
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();// 得到数据流
                    long length = entity.getContentLength();// 得到数据流长度
                    InputStream is = entity.getContent();// 得到数据流内容
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(
                                

Environment.getExternalStorageDirectory()
                                        + "/version.xml");
                        fileOutputStream = new FileOutputStream(file);

                        byte[] buf = new byte[1024];
                        int ch = -1;// 一次从输入流读取的字节长度
                        int count = 0;// 总共读取的长度
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            if (length > 0) {// 如果length>0表示还有没下载

完的数据
                                length = length - ch;
                            }
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    void ReadXML() {
        DocumentBuilderFactory docBuilderFactory = null;
        DocumentBuilder docBuilder = null;
        Document doc = null;
        try {
            docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilder = docBuilderFactory.newDocumentBuilder();
            // xml file 放到 assets目录中的
            File f = new File(Environment.getExternalStorageDirectory()
                    + "/version.xml");
            InputStream is = new FileInputStream(f);
            doc = docBuilder.parse(is);
            // root element
            Element root = doc.getDocumentElement();
            // Do something here
            // get a NodeList by tagname
            NodeList nodeList = root.getElementsByTagName("string");
            Element nd = (Element) nodeList.item(0);
            // serverVersion = Integer.parseInt(nd.getNodeValue());
            String s = nd.getChildNodes().item(0).getNodeValue().toString();
            serverVersion = Float.parseFloat(s);
        } catch (IOException e) {
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
        } finally {
            doc = null;
            docBuilder = null;
            docBuilderFactory = null;
        }
    }

    public void checkVersion() {
        if (localVersion < serverVersion) {
            // 发现新版本,提示用户更新
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("软件升级")
                    .setMessage("发现新版本,建议立即更新使用.")
                    .setPositiveButton("更新",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface

dialog,
                                        int which) {
                                    pBar = new ProgressDialog

(Update.this);
                                    pBar.setTitle("正在下载");
                                    pBar.setMessage("请稍候...");
                                    pBar.setProgressStyle

(ProgressDialog.STYLE_SPINNER);

                                    // 这里的url要改成下载的服务器

的地址
                                    downFile

("http://60.171.56.198:8000/Home/Download");
                                }
                            })
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface

dialog,
                                        int which) {
                                    dialog.dismiss();
                                }
                            });
            alert.create().show();
        }
    }

    void downFile(final String url) {
        pBar.show();
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();// 得到数据流
                    long length = entity.getContentLength();// 得到数据流长度
                    InputStream is = entity.getContent();// 得到数据流内容
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File("/sdcard/update.apk");
                        fileOutputStream = new FileOutputStream(file);

                        byte[] buf = new byte[1024];
                        int ch = -1;// 一次从输入流读取的字节长度
                        int count = 0;// 总共读取的长度
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            if (length > 0) {// 如果length>0表示还有没下载

完的数据
                                length = length - ch;
                            }
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    down();// 关闭滚动条并打开刚刚下载的最新版本安装程序
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    void down() {
        handler.post(new Runnable() {
            public void run() {
                pBar.cancel();
                Toast.makeText(Update.this, "下载完毕,开始安装", Toast.LENGTH_LONG)
                        .show();
                update();
            }
        });
    }

    void update() {// 打开更新的安装程序
        File file = new File("/sdcard/update.apk");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

}

另外附上version.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<Versions>
    <Version>
        <versionCode>2.0</versionCode>
    </Version>
</Versions>


猜你喜欢

转载自blog.csdn.net/cz285933169/article/details/6420257
今日推荐