«

安卓自动更新功能实现+安卓调用默认浏览器打开指定URL

时间:2024-3-2 19:10     作者:韩俊     分类: Android


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

    Intent intent = new Intent();        
        intent.setAction("android.intent.action.VIEW");    
        Uri content_url = Uri.parse("http://www.baidu.com");   
        intent.setData(content_url);  
        startActivity(intent);打开浏览器
        System.exit(0);//退出当前APP

打开指定网页 注意加



自动更新原理

APP有一个叫版本号的属性 对比远程服务器上的版本号

如果服务器上的版本号>APP版本 则根据服务器上的下载地址 下载新的版本 之后安装 (会自动覆盖之前的版本)

服务器版本号和下载地址用XML储存 :

<update>
<version>3</version>
<name>baidu_xinwen_1.1.0</name>
<url>http://www.wangfuxin.com/UpdateSoftDemo.apk</url>
</update>

下边一个类为更新类 包括判断版本 执行下载 安装
package com.szy.update;

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.URL;
import java.util.HashMap;

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.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 *@author coolszy
 *@date 2012-4-26
 *@blog http://blog.92coding.com
 */

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 boolean checkUpdate()
    {
        if (isUpdate())
        {

            showNoticeDialog();
            return false;
        } else
        {
            return true;
        }
    }
    public InputStream getInputStreamFromUrl(String urlStr)//根据URL获取XML文件
            throws MalformedURLException, IOException {
        URL  url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConn.getInputStream();
        return inputStream;
    }

    private boolean isUpdate()
    {

        int versionCode = getVersionCode(mContext);
        try
        {
        InputStream inStream =getInputStreamFromUrl("http://www.wangfuxin.com/version.xml");//XML地址

        ParseXmlService service = new ParseXmlService();

            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.szy.update", 0).versionCode;
        } catch (NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return versionCode;
    }

    private void showNoticeDialog()
    {

        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(R.string.soft_update_info);

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

                //如果用户单击更新
                showDownloadDialog();
            }
        });

        builder.setNegativeButton(R.string.soft_update_later, new OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                //如果用户选择稍后跟新()
                dialog.dismiss();
                    //直接退出。。。。当然你可以不这么干
                    System.exit(0);
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    private void showDownloadDialog()
    {

        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_updating);

        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(R.string.soft_update_cancel, 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);
    }
}

上边的类用到了一个XML解析的类在这里
package com.szy.update;

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


之后是调用方法
package com.szy.update;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity
{
    boolean a=true;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
                UpdateManager manager = new UpdateManager(MainActivity.this);
        if(manager.checkUpdate())//不加这个判断的话 会同步执行下边的代码 所以加了这个 你也可以去掉试试
        {                        //checkUpdate这个会自动判断是否为新版本 然后提示 是否更新 之后执行相关的操作
            //如果是最新版本 则
                }
        else
        {
          //否则这里什么也不用写    
        }
    }

}

文章借鉴了:coolszy的博文 在他的基础上添加了 远程XML的访问 跟判断
有任何问题欢迎留言

标签: android

热门推荐