android在线升级

这个是目前项目用到的,没有本地自动安装,记录下来,以后的项目好用。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;

import com.ladongjiguang.meikuangwuziyunshu.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;


public class UpdateManager {

    private static final int DOWNLOAD = 1;

    private static final int DOWNLOAD_FINISH = 2;

    HashMap<String, String> mHashMap;

    private String mSavePath;

    private int progress;

    private boolean cancelUpdate = false;

    private Context mContext;

    private ProgressBar mProgress;
    private Dialog mDownloadDialog;

    private Handler mHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {

                case DOWNLOAD:

                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:

                    installApk();
                    break;
                default:
                    break;
            }
        }
    };

    public UpdateManager(Context context)
    {
        this.mContext = context;
    }


    public void checkUpdate()throws Resources.NotFoundException, IOException {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    if (isUpdate()) {
                        // 显示提示对话框
                        Looper.prepare();
                        showNoticeDialog();
                        Looper.loop();
//                        Log.d("消息", "有新版本");
                    } else {
//                        Log.d("消息", "已是最新版本");
                        Handler.sendEmptyMessage(0);
                    }
                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }
//    {
//        if (isUpdate())
//        {
//            showNoticeDialog();
//        } else
//        {
//            Toast.makeText(mContext, "此为最新版本,无需升级", Toast.LENGTH_LONG).show();
//        }
//    }

    /**
     * 土司提示
     * */
    private Handler Handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    toastMessage();
                    break;
                default:
                    break;
            }
        }

    };
    protected void toastMessage(){
        Toast.makeText(mContext, "此为最新版本,无需升级", Toast.LENGTH_LONG).show();
    }
    private boolean isUpdate() {

        URL url=null;
        try {
            url = new URL("http://211.100.56.230:37184//mhy//version.xml");//安装包地址
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }




        int versionCode = getVersionCode(mContext);

        HttpURLConnection conn = null;
        InputStream inStream=null;
        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (IOException e2) {
            e2.printStackTrace();
        }//基于HTTP协议连接对象
        conn.setConnectTimeout(5000);
        try {
            conn.setRequestMethod("GET");
        } catch (ProtocolException e1) {
            e1.printStackTrace();
        }
        try {
            if(conn.getResponseCode() == 200){
                inStream = conn.getInputStream();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }





        ParseXmlService service = new ParseXmlService();
        try {
            mHashMap = service.parseXml(inStream);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        if (null != mHashMap) {
            int serviceCode = Integer.valueOf(mHashMap.get("version"));

            if (serviceCode > versionCode) {
                return true;
            }
        }
        return false;
    }


    private int getVersionCode(Context context)
    {
        int versionCode = 0;
        try {

            versionCode = context.getPackageManager().getPackageInfo("com.ladongjiguang.meikuangwuziyunshu", 0).versionCode;//包名
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    private void showNoticeDialog()
    {

        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("发现新版本");
        builder.setMessage("是否需要更新?");

        builder.setPositiveButton("是", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();

                showDownloadDialog();
            }
        });

        builder.setNegativeButton("否", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }


    private void showDownloadDialog()
    {

        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("正在更新新版本");

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);

        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();

        downloadApk();
    }


    private void downloadApk() {

        new downloadApkThread().start();
    }


    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {

                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(mHashMap.get("url"));

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();

                    int length = conn.getContentLength();

                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);

                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, mHashMap.get("name"));
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;

                    byte buf[] = new byte[1024];

                    do {
                        int numread = is.read(buf);
                        count += numread;

                        progress = (int) (((float) count / length) * 100);

                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {

                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }

                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            mDownloadDialog.dismiss();
        }
    };


    private void installApk() {
        File apkfile = new File(mSavePath, mHashMap.get("name"));
        if (!apkfile.exists())
        {
            return;
        }

        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }
}


import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ParseXmlService
{
	public HashMap<String, String> parseXml(InputStream inStream) throws Exception
	{
		HashMap<String, String> hashMap = new HashMap<String, String>();

		// 实例化一个文档构建器工厂
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 通过文档构建器工厂获取一个文档构建器
		DocumentBuilder builder = factory.newDocumentBuilder();
		// 通过文档通过文档构建器构建一个文档实例
		Document document = builder.parse(inStream);
		//获取XML文件根节点
		Element root = document.getDocumentElement();
		//获得所有子节点
		NodeList childNodes = root.getChildNodes();
		for (int j = 0; j < childNodes.getLength(); j++)
		{
			//遍历子节点
			Node childNode = (Node) childNodes.item(j);
			if (childNode.getNodeType() == Node.ELEMENT_NODE)
			{
				Element childElement = (Element) childNode;
				//版本号
				if ("version".equals(childElement.getNodeName()))
				{
					hashMap.put("version",childElement.getFirstChild().getNodeValue());
				}
				//软件名称
				else if (("name".equals(childElement.getNodeName())))
				{
					hashMap.put("name",childElement.getFirstChild().getNodeValue());
				}
				//下载地址
				else if (("url".equals(childElement.getNodeName())))
				{
					hashMap.put("url",childElement.getFirstChild().getNodeValue());
				}
			}
		}
		return hashMap;
	}
}

引用方法:

UpdateManager manager = new UpdateManager(getActivity());
                try {
                    manager.checkUpdate();
                } catch (IOException e) {
                    e.printStackTrace();
                }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值