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

Android Studio 實現 APK 版本更新:檢測、下載與自動安裝全流程

編輯:關於 Android 程式設計

先放幾張效果圖,讓大家對要做成什麼樣有個概念:

原理大家都懂,就不囉嗦了,直接看程式碼。裡面有幾段是我自己拿來測試的雜項,你可以直接刪掉。

一、主介面 activity_main.xml

一個「任務索取」按鈕、一個 ListView 佔位,再加一顆觸發更新的按鈕:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.fucm.wms_jianh.MainActivity">

    <Button
        android:id="@+id/btn_sq"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="197dp"
        android:text="@string/btn_sq" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/btn_sq" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_sq"
        android:layout_centerHorizontal="true"
        android:text="更新" />
</RelativeLayout>

二、MainActivity.java

這裡有個容易忽略的細節:Android 4.0 之後在主執行緒做網路請求會拋 NetworkOnMainThreadException,所以我在 onCreate 裡先打開 StrictMode 的寬鬆策略,方便測試。正式專案應該把網路請求扔到子執行緒,別學我。

public class MainActivity extends Activity implements OnClickListener {

    Button btn1, btn2;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 僅為測試方便,正式環境請改用非同步執行緒
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());

        setContentView(R.layout.activity_main);
        btn1 = (Button) findViewById(R.id.btn_sq);
        btn2 = (Button) findViewById(R.id.button);
        btn1.setOnClickListener(this);
        listView = (ListView) findViewById(R.id.listView);

        btn2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SoftUpdate manager = new SoftUpdate(MainActivity.this);
                manager.checkUpdate();   // 檢查更新
            }
        });
    }
}

三、HttpHelper.java

負責 GET 請求與 JSON 解析。這裡用的是老寫法 DefaultHttpClient,新專案建議換成 OkHttp 或 HttpURLConnection。

public class HttpHelper {

    private static final int REQUEST_TIMEOUT = 15 * 1000;
    private static final int SO_TIMEOUT = 15 * 1000;

    public static String sendHttpRequest(String pUrl) {
        return doGet(pUrl);
    }

    public static String doGet(String url) {
        String result = null;
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return null;
            }
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    // 解析形如 {"d":{"a":"..."}} 的結構
    public static String GetJsonListValue(String str) {
        try {
            JSONObject json1 = new JSONObject(str);
            JSONObject tmp = json1.getJSONObject("d");
            return tmp.getString("a");
        } catch (Exception e) {
            return e.toString();
        }
    }

    public static JSONArray GetJsonValue(String str) {
        try {
            return new JSONArray(str);
        } catch (Exception e) {
            return null;
        }
    }
}

四、SoftUpdate.java(核心)

整個更新流程都在這裡:比對版本號 → 彈提示框 → 顯示進度框並下載 → 下載完畢觸發安裝。

public class SoftUpdate {

    private static final int DOWNLOAD = 1;         // 下載中
    private static final int DOWNLOAD_FINISH = 2;  // 下載結束

    private Long str_version;      // 伺服器版本號
    private String str_appname;    // 檔案名稱
    private String str_downurl;    // 下載位址
    private String mSavePath;      // 儲存路徑
    private int progress;          // 進度
    private boolean cancelUpdate = false;
    private Context mContext;
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;

    public SoftUpdate(Context context) {
        this.mContext = context;
    }

    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 void checkUpdate() {
        if (isUpdate()) {
            showNoticeDialog();
        } else {
            Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
        }
    }

    /** 比對本地與伺服器版本號 */
    private boolean isUpdate() {
        int versionCode = getVersionCode(mContext);
        try {
            String str = HttpHelper.sendHttpRequest(
                    "https://127.0.0.1/Service1.svc/get_version");
            JSONArray json1 = HttpHelper.GetJsonValue(str);
            str_version = json1.getLong(0);
            str_appname = json1.getString(1);
            str_downurl = json1.getString(2);
            return str_version > versionCode;
        } catch (Exception e) {
            return false;
        }
    }

    /** 讀取本地 versionCode,對應 Manifest 的 android:versionCode */
    private int getVersionCode(Context context) {
        try {
            return context.getPackageManager()
                    .getPackageInfo("com.example.fucm.wms_jianh", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /** 更新提示框 */
    private void showNoticeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(R.string.soft_update_info);
        builder.setPositiveButton(R.string.soft_update_updatebtn,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showDownloadDialog();
                    }
                });
        builder.setNegativeButton(R.string.soft_update_later,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }

    /** 下載進度框 */
    private void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.soft_updating);
        View v = LayoutInflater.from(mContext).inflate(R.layout.soft_update, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        builder.setNegativeButton(R.string.soft_update_cancel,
                new DialogInterface.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(str_downurl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    File dir = new File(mSavePath);
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                    File apkFile = new File(mSavePath, str_appname);
                    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();
        }
    }

    /** 用 Intent 交給系統安裝器 */
    private void installApk() {
        File apkfile = new File(mSavePath, str_appname);
        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);
    }
}

這裡有個實務上會踩到的雷:Android 7.0 之後 file:// 形式的 Uri 會觸發 FileUriExposedException,必須改用 FileProvider 並在 Manifest 中宣告,同時給臨時讀取權限。另外 ACTION_VIEW 安裝需要 REQUEST_INSTALL_PACKAGES 權限,Android 8.0 起還要引導使用者手動開啟「安裝未知應用」。

五、soft_update.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/update_progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

六、AndroidManifest.xml

三個權限缺一不可:網路、寫入外部儲存,以及掛載/卸載檔案系統(老版本需要)。

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.fucm.wms_jianh"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

    <application>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".RwdMxActivity" />
    </application>
</manifest>

記得:WRITE_EXTERNAL_STORAGE 從 Android 6.0 開始屬於危險權限,必須執行期動態申請,否則寫檔會靜默失敗。

七、strings.xml

<resources>
    <string name="app_name">WMS_JIANH</string>
    <string name="btn_sq">任務索取</string>
    <string name="soft_update_no">已經是最新版本</string>
    <string name="soft_update_title">軟體更新</string>
    <string name="soft_update_info">檢測到新版本,立即更新嗎</string>
    <string name="soft_update_updatebtn">更新</string>
    <string name="soft_update_later">稍後更新</string>
    <string name="soft_updating">正在更新</string>
    <string name="soft_update_cancel">取消</string>
</resources>

八、工程結構

整體就三塊:HttpHelper 負責取版本資訊、SoftUpdate 負責流程與下載、Activity 負責觸發。串起來就是一個可用的 App 內更新機制。

原始碼下載:https://yunpan.cn/cBFKmGJKqiLct 訪問密碼 6e01

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