Android下載更新代碼

來源:互聯網
上載者:User

標籤:

其實是昨天反編譯一個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===========

 

Android下載更新代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.