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();
                }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章