Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 應用檢查更新全流程總結:從 Splash 到自動升級

編輯:關於 Android 程式設計

幾乎每個應用在進入主界面前,都會有一個啟動頁用來展示品牌信息、介紹軟件,並順手完成版本檢查、及時提醒用戶升級。良好的升級體驗能顯著改善用戶留存。本文把整個流程整理一遍,以後要用時不必到處翻項目。

習慣上,我們把實現這個功能的 Activity 命名為 SplashActivity。

進入這個界面後,通常需要初始化一批數據:把內置文件複製到應用目錄、把打包的數據庫釋放到系統目錄、以及檢查版本是否需要更新等。

一、複製文件到應用目錄

複製邏輯比較通用,只要拿到源路徑和目標路徑即可。獲取 SD 卡上的文件列表:

/**
 * 獲得文件路徑和狀態信息
 * @return
 */
private List<MyFileInfo> getFiles() {
    File path = null;
    List<MyFileInfo> infos = new ArrayList<MyFileInfo>();
    MyFileInfo info = null;
    // 判斷 SD 卡是否可用
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        path = Environment.getExternalStorageDirectory();
        File[] files = path.listFiles();
        for (File file : files) {
            if (file.getPath() != null) {
                info = new MyFileInfo();
                info.setPath(file.getPath());
                infos.add(info);
                info = null;
            }
        }
    } else {
        Toast.makeText(FileSearchActivity.this, "SD卡不可用!", 300).show();
    }
    return infos;
}

通用複製方法(這裡用 512 字節的緩衝區,實戰中建議調大到 4KB 以上以減少 IO 次數):

/**
 * 文件複製
 * @param res  源文件路徑
 * @param des  目標文件路徑
 * @return 是否成功
 */
public static boolean toCopy(String res, String des) {
    boolean flag = false;
    File file = new File(res);
    FileInputStream fr = null;
    File desFile = new File(des);
    FileOutputStream bw = null;
    try {
        fr = new FileInputStream(file);
        bw = new FileOutputStream(desFile);
        byte[] b = new byte[512];
        while (fr.read(b) != -1) {
            bw.write(b);
        }
        bw.flush();
        flag = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fr != null) {
            try { fr.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        if (bw != null) {
            try { bw.close(); } catch (IOException e) { e.printStackTrace(); }
        }
    }
    return flag;
}

獲取應用的私有目錄:

File file = new File(getFilesDir(), "xxx.xls");
// 對應 data/data/包名/files 目錄

這樣就能把 SD 卡上的文件複製到應用私有目錄了。

二、釋放內置數據庫

如果應用了預置數據庫,需要在首次啟動時把它從 assets 複製到應用目錄。

(1)確定目標路徑:

final File file = new File(getFilesDir(), "xxx.db");

(2)打開資產目錄中的數據庫輸入流:

InputStream is = getAssets().open("xxx.db");

關於讀取資源,有兩種常見方式:

  • 讀取 res/raw 下的資源:InputStream is = getResources().openRawResource(R.raw.filename);
  • 讀取 assets 下的資源:AssetManager am = getAssets(); InputStream is = am.open("filename");

(3)複製完成後打開數據庫並獲取引用的工具類:

public class CopyFileToSystem {

    /**
     * 把文件拷貝到系統文件夾
     * @param in       輸入流
     * @param destPath 目標路徑
     */
    public static void copyFile(InputStream in, String destPath) {
        File file = new File(destPath);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) fos.close();
                if (in != null) in.close();
            } catch (IOException e) { }
        }
    }
}

(4)以只讀方式打開並操作數據庫:

SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);

注意:拷貝到系統的數據庫路徑為 /data/data/應用包名/files/數據庫文件名,而自己通過 SQLiteOpenHelper 建立的數據庫則位於 databases 目錄下,兩者不要混淆。

三、檢查更新

第一步:獲取當前應用版本號。

/**
 * 獲得應用的版本號
 * @return
 */
private String getAppVersion() {
    PackageManager pm = getPackageManager();
    PackageInfo info = null;
    try {
        info = pm.getPackageInfo(getPackageName(), 0);
        if (info != null) {
            return info.versionName;
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    return "";
}

第二步:連接服務器解析配置,拿到最新版本號。

服務器端的 XML 設計得很簡單:

<?xml version="1.0" encoding="utf-8"?>
<info>
    <version>2.0</version>
    <description>空降新版本,請下載,體驗更多新特性!!!</description>
    <apkurl>https://192.168.253.1:8080/TouristManager.apk</apkurl>
</info>

解析類用 XmlPullParser 實現:

public class UpdateInfoParser {

    /**
     * 解析服務器返回的更新信息
     * @param is 服務器返回的流
     * @return 解析失敗返回 null
     */
    public static UpdateInfo getUpdateInfo(InputStream is) {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(is, "utf-8");
            int type = parser.getEventType();
            UpdateInfo info = null;
            while (type != XmlPullParser.END_DOCUMENT) {
                switch (type) {
                    case XmlPullParser.START_TAG:
                        if ("info".equals(parser.getName())) {
                            info = new UpdateInfo();
                        } else if ("version".equals(parser.getName())) {
                            info.setVersion(parser.nextText());
                        } else if ("description".equals(parser.getName())) {
                            info.setDescription(parser.nextText());
                        } else if ("apkurl".equals(parser.getName())) {
                            info.setApkurl(parser.nextText());
                        }
                        break;
                }
                type = parser.next();
            }
            return info;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

第三步:SplashActivity 串起整個流程。核心是用 Handler 加子線程完成網絡請求,並用狀態碼區分各種失敗情況,最後決定「進入主界面」還是「彈出升級對話框」。

public class SplashActivity extends Activity {

    private TextView mTVversion;   // 顯示應用的版本
    private String mVersion;

    public static final int PARSE_XML_ERROR = 10;
    public static final int PARSE_XML_SUCCESS = 11;
    public static final int SERVER_ERROR = 12;
    public static final int URL_ERROR = 13;
    public static final int NETWORK_ERROR = 14;
    private static final int DOWNLOAD_SUCCESS = 15;
    private static final int DOWNLOAD_ERROR = 16;
    protected static final String TAG = "SplashActivity";
    private static final int COPYDATA_ERROR = 17;

    private UpdateInfo updateInfo;
    private ProgressDialog pd;   // 下載進度對話框

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case PARSE_XML_ERROR:
                    Toast.makeText(getApplicationContext(), "解析xml失敗", 0).show();
                    loadMainUI();
                    break;
                case SERVER_ERROR:
                    Toast.makeText(getApplicationContext(), "服務器異常", 0).show();
                    loadMainUI();
                    break;
                case URL_ERROR:
                    Toast.makeText(getApplicationContext(), "服務器地址異常", 0).show();
                    loadMainUI();
                    break;
                case NETWORK_ERROR:
                    Toast.makeText(getApplicationContext(), "網絡異常", 0).show();
                    loadMainUI();
                    break;
                case PARSE_XML_SUCCESS:
                    if (getAppVersion().equals(updateInfo.getVersion())) {
                        Log.i(TAG, "版本號相同,進入主界面");
                        loadMainUI();
                    } else {
                        Log.i(TAG, "版本號不相同,彈出來升級提示對話框");
                        showUpdateDialog();
                    }
                    break;
                case DOWNLOAD_ERROR:
                    Toast.makeText(getApplicationContext(), "下載失敗", 0).show();
                    loadMainUI();
                    break;
                case DOWNLOAD_SUCCESS:
                    File file = (File) msg.obj;
                    Log.i(TAG, "安裝apk" + file.getAbsolutePath());
                    installApk(file);
                    finish();
                    break;
                case COPYDATA_ERROR:
                    Toast.makeText(getApplicationContext(), "加載數據庫失敗", 0).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        intiViews();
    }

    private void intiViews() {
        setContentView(R.layout.activity_splash);
        mTVversion = (TextView) this.findViewById(R.id.app_version);
        mVersion = getAppVersion();
        mTVversion.setText(mVersion);
        // 連接服務器檢查版本更新
        new Thread(new CheckVersionTask()).start();
        AlphaAnimation aa = new AlphaAnimation(0.2f, 1.0f);
        aa.setDuration(2000);
        findViewById(R.id.rl_splash).startAnimation(aa);
    }

    private void loadMainUI() {
        Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
        startActivity(intent);
        this.finish();
    }

    // 升級提示對話框
    protected void showUpdateDialog() {
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("升級提醒");
        builder.setMessage(updateInfo.getDescription());
        builder.setPositiveButton("確定", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String apkurl = updateInfo.getApkurl();
                pd = new ProgressDialog(SplashActivity.this);
                pd.setTitle("升級操作");
                pd.setMessage("正在下載...");
                pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pd.show();
                final File file = new File(Environment.getExternalStorageDirectory(),
                        DownLoadUtil.getFileName(apkurl));
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    new Thread() {
                        public void run() {
                            File savedFile = DownLoadUtil.download(
                                    updateInfo.getApkurl(), file.getAbsolutePath(), pd);
                            Message msg = Message.obtain();
                            if (savedFile != null) {
                                msg.what = DOWNLOAD_SUCCESS;
                                msg.obj = savedFile;
                            } else {
                                msg.what = DOWNLOAD_ERROR;
                            }
                            handler.sendMessage(msg);
                            pd.dismiss();
                        }
                    }.start();
                } else {
                    Toast.makeText(getApplicationContext(), "sd卡不可用", 0).show();
                    loadMainUI();
                }
            }
        });
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                loadMainUI();
            }
        });
        builder.create().show();
    }

    // 檢查更新的後台任務
    private class CheckVersionTask implements Runnable {
        @Override
        public void run() {
            SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
            boolean isupdate = sp.getBoolean("update", true);
            if (!isupdate) {
                try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
                loadMainUI();
                return;
            }
            long startTime = System.currentTimeMillis();
            Message msg = Message.obtain();
            try {
                URL url = new URL(getResources().getString(R.string.serverurl));
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(1500);
                int code = conn.getResponseCode();
                if (code == 200) {
                    InputStream is = conn.getInputStream();
                    updateInfo = UpdateInfoParser.getUpdateInfo(is);
                    msg.what = (updateInfo == null) ? PARSE_XML_ERROR : PARSE_XML_SUCCESS;
                } else {
                    msg.what = SERVER_ERROR;
                }
            } catch (MalformedURLException e) {
                msg.what = URL_ERROR;
            } catch (NotFoundException e) {
                msg.what = URL_ERROR;
            } catch (IOException e) {
                msg.what = NETWORK_ERROR;
                e.printStackTrace();
            } finally {
                // 保證啟動頁至少展示 2 秒,避免閃屏過快影響品牌呈現
                long dTime = System.currentTimeMillis() - startTime;
                if (dTime < 2000) {
                    try { Thread.sleep(2000 - dTime); } catch (InterruptedException e) { }
                }
                handler.sendMessage(msg);
            }
        }
    }

    // 安裝 apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }
}

第四步:下載工具類。

public class DownLoadUtil {

    /**
     * 下載文件
     * @param serverPath 服務器文件路徑
     * @param savedPath  本地保存路徑
     * @param pd         進度條對話框
     * @return 成功返回文件對象,失敗返回 null
     */
    public static File download(String serverPath, String savedPath, ProgressDialog pd) {
        try {
            URL url = new URL(serverPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            int code = conn.getResponseCode();
            if (code == 200) {
                pd.setMax(conn.getContentLength());
                InputStream is = conn.getInputStream();
                File file = new File(savedPath);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int len = 0;
                int total = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    total += len;
                    pd.setProgress(total);
                    Thread.sleep(20);
                }
                fos.flush();
                fos.close();
                is.close();
                return file;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /** 從 URL 中截取文件名 */
    public static String getFileName(String serverPath) {
        return serverPath.substring(serverPath.lastIndexOf("/") + 1);
    }
}

四、幾點實踐建議

版本比較不要只用字符串相等。1.0 與 1.0.0 用 equals 比較會判斷為不同,而 1.10 與 1.9 按字符串比較大小也會出錯。建議把版本號拆成整數逐段比較,或者約定使用單調遞增的 versionCode 來判斷。

強升級與弱升級要區分。可以在服務器配置中加一個標志位:強升級時對話框不提供「取消」;弱升級則允許用戶跳過。這兩種策略在實際產品中都需要。

下載目錄與存儲權限。新版本 Android 對外部存儲的訪問限制越來越嚴格,下載 APK 時應優先選擇應用私有目錄(getExternalFilesDir()),並通過 FileProvider 提供 URI,否則會出現「解析安裝包失敗」。

安裝環節的 FileUriExposedException。Android 7.0 之後禁止直接暴露 file:// URI,必須改用 FileProvider.getUriForFile() 並授權 FLAG_GRANT_READ_URI_PERMISSION,這是這一整套流程在新系統上最容易失敗的一環。

別忘了失敗兜底。網絡異常、服務器 5xx、XML 解析失敗等情況都可能發生,任何一種都不應該讓用戶卡在啟動頁。上面的代碼在每個錯誤分支都調用了 loadMainUI(),就是為了保證這一點。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved