溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

android 應(yīng)用自身檢測版本并下載

發(fā)布時間:2020-06-27 01:58:02 來源:網(wǎng)絡(luò) 閱讀:604 作者:巡洋艦cool 欄目:移動開發(fā)

思路:1在服務(wù)器固定目錄存放固定的了版本文件;

           2.應(yīng)用請求服務(wù)器端的版本文件,判斷是否有最新版本;

     3.創(chuàng)建下載連接,下載最新apk;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Xml;


/**
 * Created by shijian on 15-8-13.
 * 檢查應(yīng)用版本
 */
public class CheckVersionUtil {

    public void checkVersion(Context context) {

        this.context = context;
        threadPool.execute(checkVersion);
    }

    /**
     * 檢查版本線程
     * @author shijian
     */
    Runnable checkVersion = new Runnable() {

        @Override
        public void run() {

            try {
                //從清單文件中獲得當(dāng)前版本號
                PackageInfo info = context.getPackageManager().getPackageInfo("cn.com.shijian.test", 0);
                float localVersion = Float.valueOf(info.versionName);
                float serverVersion = 0;

                //版本文件在服務(wù)器上的路徑
                String versionPath = CommonUtil.prefixUrl + File.separator + context.getString(R.string.apkversionUrl);

                URL url = new URL(versionPath);

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

                //讀入XML文件輸入流
                InputStream input = conn.getInputStream();
                //解析XML文件
                XmlPullParser parser = Xml.newPullParser();
                try {
                    parser.setInput(input, "utf-8");
                    int eventType = parser.getEventType();

                    while(eventType != XmlPullParser.END_DOCUMENT) {

                        switch (eventType) {

                            case XmlPullParser.START_TAG:

                                //版本
                                if ("version".equals(parser.getName())) {

                                    serverVersion = Float.valueOf(parser.nextText());
                                }
                                //是否強(qiáng)制更新
                                if("ismustupdate".equals(parser.getName())){
                                    ismustupdate = parser.nextText();
                                }
                                if ("description".equals(parser.getName())) {
                                    //換行
                                    description = parser.nextText().replace("\\n", "\n");
                                }
                                break;
                        }
                        eventType = parser.next();
                    }
                    //如果服務(wù)器版本號大于本地版本號
                    if (serverVersion > localVersion) {

                        boolean post = handler.post(new Runnable() {
                            @Override
                            public void run() {

                                Builder builder = new Builder(context);
                                builder.setTitle("版本升級");
                                builder.setMessage(description);
                                builder.setPositiveButton("下載最新版", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        downloadApk();
                                    }
                                });

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

                                AlertDialog dialog = builder.create();
                                dialog.show();
                            }
                        });
                        //當(dāng)前版本是最新版
                    } else if (serverVersion <= localVersion) {
                        if (context.getClass().equals(HomeActivity.class)) {
                            return;
                        }
                        handler.post( new Runnable() {
                            public void run() {

                                AlertDialog.Builder builder = new Builder(context);
                                builder.setTitle("版本升級");
                                builder.setMessage("已經(jīng)是最新版本");
                                AlertDialog dialog = builder.create();
                                dialog.show();
                            }
                        });

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


            } catch (NameNotFoundException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

                threadPool.shutdown();
            }
        }
    };



    /**
     *
     * 點(diǎn)擊下載apk
     * @author shijian
     * @since 2015-8-13
     */
    public void downloadApk() {

        //獲得DownloadManager
        final DownloadManager downloadMgr = (DownloadManager)  context.getSystemService(Context.DOWNLOAD_SERVICE);
        //定義下載URI
        Uri apkLocation = Uri.parse(CommonUtil.prefixUrl + File.separator + context.getString(R.string.apkUrl));

        Request  request = new Request(apkLocation);
        //request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
        request.setTitle("e車問更新");
        //如果文件件不存在則建立
        File folder = Environment.getExternalStoragePublicDirectory("echewen");
        if (folder.exists() && folder.isDirectory()){

        } else {
            folder.mkdirs();
        }

        //如果echewen.apk已經(jīng)存在刪除掉,防止出現(xiàn)多個
        File apk = new File(CheckVersionUtil.APK_UPDATE);
        if (apk.exists()) {
            apk.delete();
        }
        //保存下載的文件到指定目錄下
        request.setDestinationInExternalPublicDir("echewen", "echewen.apk");
        //該downloadmanager的ID
        final long ref = downloadMgr.enqueue(request);

        IntentFilter filter =  new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

        BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                long mRef = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                if (mRef == ref) {

                    Cursor c = downloadMgr.query(new DownloadManager.Query().setFilterById(mRef));
                    c.moveToFirst();
                    String downloadFile = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                    Intent installIntent = new Intent(Intent.ACTION_VIEW);
                    installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    installIntent.setDataAndType(Uri.parse(downloadFile),
                            "application/vnd.android.package-archive");//設(shè)置intent的數(shù)據(jù)類型

                    context.startActivity(installIntent);
                }
            }
        };
        context.registerReceiver(receiver, filter);
    }
    //線程池
    ExecutorService threadPool = Executors.newCachedThreadPool();
    Handler handler = new Handler();
    //版本升級說明
    String description;
    //上下文
    Context context;

    String ismustupdate = "0";//0:必須更新;1:不必須


    public static final String APK_UPDATE = Environment.getExternalStorageDirectory().getPath() + "/echewen/echewen.apk";
    public static final String STORAGE_IMAGE_PATH = Environment.getExternalStorageDirectory().getPath() + "/echewen/apk/";

}


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI