Android下载更新代码

其实是昨天反编译一个apk,给它添加一个自动更新的功能用到的。为了在smali下方便查看,代码写的不规范,反正到了smali都一个吊样~~~~

权限:
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    //Start===========
    public void updata(){
        new Thread(){
            @Override
            public void run() {
                request(apiUrl);
            }
        }.start();

    }
    String newapkName = "updata.apk";
    String apiUrl = "http://192.168.1.101:8080/udate.txt";
    //请求接口
    public void request(String Httpurl){
        URL url = null;
        try {
            url = new URL(Httpurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream is = conn.getInputStream();
            String s = toString(is);
            JSONObject jsonObject = new JSONObject(s);
            Double versionCode = jsonObject.getDouble("versionCode"); //远程版本
            String versionName = getVersionName();
            double v = Double.parseDouble(versionName);
            if(versionCode > v){
                //更新下载
                downLoadFile(jsonObject.getString("updateurl"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    ShowUpdataDilg();
                    break;

            }
        }
    };
    //版本提示对话框
    public void ShowUpdataDilg() {
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("提示")
                .setMessage("是否安装最新版本? ")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Uodate();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

    //获取版本
    private String getVersionName() throws Exception
    {
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名,0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }

    //安装apk
    public void Uodate(){
//        String str = "/" + newapkName;
//        String fileName = Environment.getExternalStorageDirectory() + str;
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
//        startActivity(intent);

        String str = "/sdcard/update/" + newapkName;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(str)),
                "application/vnd.android.package-archive");
        startActivity(intent);

    }

//对话框确定
    public void isUpdate(){
        String str = "/" + newapkName;
        String fileNames = Environment.getExternalStorageDirectory() + str;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(fileNames)), "application/vnd.android.package-archive");
        startActivity(intent);

    }

    protected File downLoadFile(String httpUrl) {
        File tmpFile = new File("/sdcard/update");
        if (!tmpFile.exists()) {
            tmpFile.mkdir();
        }
        final File file = new File("/sdcard/update/" + newapkName);

        try {
            URL url = new URL(httpUrl);
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                InputStream is = conn.getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[256];
                conn.connect();
                double count = 0;
                if (conn.getResponseCode() >= 400) {
                    Toast.makeText(MainActivity.this, "连接超时", Toast.LENGTH_SHORT).show();
                } else {
                    while (count <= 100) {
                        if (is != null) {
                            int numRead = is.read(buf);
                            if (numRead <= 0) {
                                break;
                            } else {
                                fos.write(buf, 0, numRead);
                            }
                        } else {
                            break;
                        }
                    }
                }
                fos.close();
                is.close();
                conn.disconnect();
                //下载成功
                handler.sendEmptyMessage(1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return file;
    }
    //输入流转换为String
    public String toString(InputStream is) {
        String result = null;
        try {
            //构造一个输出流(字节队列输出流)
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //一个byte数组,用来存储得到的字节数据
            byte[] bys = new byte[1024];
            int len = 0;
            //循环读出完整字节数据
            while((len = is.read(bys)) != -1) {
                baos.write(bys,0,len);
            }
            //byte数据转换为字符串
            result = new String(baos.toByteArray());
            is.close();
            baos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    //End===========
时间: 2024-08-28 21:50:29

Android下载更新代码的相关文章

Android SDK Manager 无法下载更新,或者更新速度超慢,或者待安装包列表不显示

解决方法: 转自 http://www.cnblogs.com/tc310/archive/2012/12/21/2828450.html http://jingyan.baidu.com/article/636f38bb267982d6b84610f0.html 第一步:修改hosts文件 修改后的hosts 文件内容为: 127.0.0.1 localhost #Google主页 203.208.46.146 www.google.com #这行是为了方便打开Android开发官网 现在好像

Android SDK 更新和下载慢怎么办?

昨天晚上安装了Android SDK,想安装指定版本,但是速度超慢,1kb/s.后来我发现了http://mirrors.neusoft.edu.cn/, 这里面有Android,如何在SDK  Manager中配置参考 http://mirrors.neusoft.edu.cn/configurations.we#android, 摘录如下 启动 Android SDK Manager ,打开主界面,依次选择「Tools」.「Options...」,弹出『Android SDK Manager

Cocos Code IDE解决ios模拟器和Android真机无法热更新代码问题

修改Runtime.cpp文件,添加一些代码 bool FileServer::receiveFile(int fd) { // ... string finish("finish\n"); send(fd, finish.c_str(), finish.size(),0); CCLOG("finish\n"); // I add these code Director::getInstance()->getScheduler()->performFun

android sdk manager无法下载更新解决办法

ping ad.doubleclick.net 查看下谷歌广告域名所指向的ip,即可获取谷歌google最新可IP,这个IP也可以用于sdk manager下载更新! 获取到新IP,修改hosts文件,添加 74.125.107.89 www.google.com 74.125.113.121 developer.android.com 74.125.107.89 dl.google.com 74.125.107.89 dl-ssl.google.com 127.0.0.1 activate.a

下载android sdk更新包离线安装解决方案

本文转载自:http://xljboox.blog.163.com/blog/static/7628448320111159354738/ 第一次安装android sdk后进行开发包的更新,你应该了解到需要的时间会很长,那么是否有办法提升安 装的进度呢?办法自然是有的,这里提供一个取巧的方法,不会太麻烦,又能加快android开发环境的部 署过程.具体请参考如下.1.通过访问和分析android更新列表的xml在线地址 *************************************

Android Studio 3.1 Beta 1发布,如何及时下载更新

每次收到Android Studio更新提示,总是延迟一段时间才能下载的到或者更新成功.架梯子也不行.而且更新检测也是时断时续.Android Studio 3.0.1使用一段时间,多开几个工程.经常发生关闭一个工程AS无响应,强制关闭其他工程也跟着关闭.这次等来了Android Studio 3.1 Beta 1更新提醒,但是不能自动更新,需要下载覆盖.提示如下:根据提示,点击下载,跳转到官网:发现只有上上一个版本的下载.翻来翻去找了几个页面都没找到最近的两个版本:Android Studio

基于Android下载并解压Zip文件,更新UI简单帮助类

类似于:http://blog.csdn.net/jarlen/article/details/44794031 下载文件: /** * 下载文件 * * @param down_url * @param output * @param tmpDir */ private void download(String down_url, File output, File tmpDir) { InputStream inputStream = null; OutputStream outputStr

Android应用更新升级实现

介绍 在产品的开发中,android升级提示,下载更新是必备的功能,否则等用户被动去官方网,或者第三方商店提示,就为时已晚了. 原理 在用户每次打开应用的时候,都与服务器进行一次交互,获取版本信息,对比之后,如果版本号大于当前版本号,那么就提示用户升级,否则就当什么都没发生. 直接看代码. 实现 权限 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission andr

Android Studio 更新

(转)http://www.cnblogs.com/daemon369/p/3266264.html Android Studio是今年5月份Google I/O 2013开发者大会上Google为Android开发者发布的一项全新的基于IntelliJ IDEA的Android开发环境. 官方网址:http://developer.android.com/sdk/installing/studio.html . 目前(2013-09-25)发布的完整安装包版本为:130.737825,可通过p