diff --git a/CHANGELOG.md b/CHANGELOG.md
index 200fafa..8b6dc6d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,13 @@ CI 规则(.gitea/workflows/release.yml):
需要更正请发补丁版本
-->
+## v1.5.0
+
+### 调整
+
+- 应用内可以直接下载并安装新版本,不再跳转浏览器;系统提示时请允许本应用安装未知应用
+- 新版本安装完成后登录状态和数据都会保留
+
## v1.4.0
### 新增
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 731ee0b..f5f1e69 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -7,8 +7,8 @@ android {
applicationId "com.imyeyu.gao.customer"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
- versionCode 2
- versionName "1.0.1"
+ versionCode 3
+ versionName "1.1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 994ef2d..1e7c891 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -38,6 +38,7 @@
+
diff --git a/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java b/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java
index ad886a2..8c7b4e3 100644
--- a/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java
+++ b/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java
@@ -14,12 +14,14 @@ import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import com.getcapacitor.BridgeActivity;
+import com.imyeyu.gao.customer.shellupdater.ShellUpdaterPlugin;
import java.util.Locale;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
+ registerPlugin(ShellUpdaterPlugin.class);
super.onCreate(savedInstanceState);
applyEdgeToEdge();
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
diff --git a/android/app/src/main/java/com/imyeyu/gao/customer/shellupdater/ShellUpdaterPlugin.java b/android/app/src/main/java/com/imyeyu/gao/customer/shellupdater/ShellUpdaterPlugin.java
new file mode 100644
index 0000000..f469f49
--- /dev/null
+++ b/android/app/src/main/java/com/imyeyu/gao/customer/shellupdater/ShellUpdaterPlugin.java
@@ -0,0 +1,151 @@
+package com.imyeyu.gao.customer.shellupdater;
+
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Build;
+import android.provider.Settings;
+import androidx.core.content.FileProvider;
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.security.MessageDigest;
+import java.util.Locale;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/// 应用外壳下载与安装
+@CapacitorPlugin(name = "ShellUpdater")
+public class ShellUpdaterPlugin extends Plugin {
+ private final ExecutorService executor = Executors.newSingleThreadExecutor();
+ private final AtomicBoolean downloading = new AtomicBoolean(false);
+ private File directory;
+ private boolean awaitingSettings;
+
+ @Override
+ public void load() {
+ directory = new File(getContext().getCacheDir(), "shell-updates");
+ executor.execute(() -> {
+ File[] files = directory.listFiles();
+ if (files == null) return;
+ // 只清 6 小时前的残留:安装期间进程可能被杀后重启,立刻删除会让安装器读不到文件
+ long cutoff = System.currentTimeMillis() - 6 * 60 * 60 * 1000L;
+ for (File file : files) {
+ if (file.isFile() && file.lastModified() < cutoff) file.delete();
+ }
+ });
+ }
+
+ /// 检查安装未知应用权限
+ @PluginMethod
+ public void canInstall(PluginCall call) {
+ JSObject result = new JSObject();
+ result.put("allowed", Build.VERSION.SDK_INT < Build.VERSION_CODES.O || getContext().getPackageManager().canRequestPackageInstalls());
+ call.resolve(result);
+ }
+
+ /// 打开本应用的安装权限设置
+ @PluginMethod
+ public void openInstallSettings(PluginCall call) {
+ try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getContext().getPackageName()));
+ awaitingSettings = true;
+ getActivity().startActivity(intent);
+ }
+ call.resolve();
+ } catch (Exception e) {
+ call.reject("无法打开安装权限设置", e);
+ }
+ }
+
+ /// 下载并校验安装包,然后打开系统安装器
+ @PluginMethod
+ public void downloadAndInstall(PluginCall call) {
+ String url = call.getString("url");
+ String sha256 = call.getString("sha256");
+ String fileName = call.getString("fileName");
+ if (url == null || sha256 == null || !sha256.matches("(?i)[0-9a-f]{64}") || fileName == null || !fileName.matches("[a-zA-Z0-9._-]+\\.apk")) {
+ call.reject("安装包参数无效");
+ return;
+ }
+ if (!downloading.compareAndSet(false, true)) {
+ call.reject("安装包正在下载");
+ return;
+ }
+ executor.execute(() -> download(call, url, sha256, fileName));
+ }
+
+ private void download(PluginCall call, String address, String expected, String fileName) {
+ File file = new File(directory, fileName);
+ HttpURLConnection connection = null;
+ try {
+ if (!directory.exists() && !directory.mkdirs()) throw new Exception("无法创建下载目录");
+ URL url = new URL(address);
+ if (!"https".equalsIgnoreCase(url.getProtocol()) && !"http".equalsIgnoreCase(url.getProtocol())) throw new Exception("下载地址无效");
+ connection = (HttpURLConnection) url.openConnection();
+ connection.setConnectTimeout(15000);
+ connection.setReadTimeout(30000);
+ connection.setInstanceFollowRedirects(true);
+ if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) throw new Exception("安装包下载失败");
+ long total = connection.getContentLengthLong();
+ long received = 0;
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ try (InputStream input = connection.getInputStream(); FileOutputStream output = new FileOutputStream(file)) {
+ byte[] buffer = new byte[32768];
+ int size;
+ while ((size = input.read(buffer)) != -1) {
+ output.write(buffer, 0, size);
+ digest.update(buffer, 0, size);
+ received += size;
+ JSObject progress = new JSObject();
+ progress.put("received", received);
+ progress.put("total", total);
+ progress.put("percent", 0 < total ? (int) Math.min(100, received * 100 / total) : 0);
+ notifyListeners("downloadProgress", progress);
+ }
+ }
+ StringBuilder actual = new StringBuilder();
+ for (byte b : digest.digest()) actual.append(String.format(Locale.ROOT, "%02x", b & 255));
+ if (!actual.toString().equalsIgnoreCase(expected)) throw new Exception("安装包校验失败");
+ Uri uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", file);
+ Intent intent = new Intent(Intent.ACTION_VIEW);
+ intent.setDataAndType(uri, "application/vnd.android.package-archive");
+ intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
+ getActivity().runOnUiThread(() -> {
+ try {
+ getActivity().startActivity(intent);
+ call.resolve();
+ } catch (Exception e) {
+ call.reject("无法打开系统安装器", e);
+ }
+ });
+ } catch (Exception e) {
+ file.delete();
+ call.reject("安装包下载或校验失败", e);
+ } finally {
+ if (connection != null) connection.disconnect();
+ downloading.set(false);
+ }
+ }
+
+ @Override
+ protected void handleOnResume() {
+ if (awaitingSettings) {
+ awaitingSettings = false;
+ notifyListeners("resume", new JSObject());
+ }
+ }
+
+ @Override
+ protected void handleOnDestroy() {
+ executor.shutdown();
+ }
+}
diff --git a/src/composables/useAppUpdate.ts b/src/composables/useAppUpdate.ts
index 2aeec2e..be7e9bc 100644
--- a/src/composables/useAppUpdate.ts
+++ b/src/composables/useAppUpdate.ts
@@ -12,13 +12,17 @@ export const APP_ID = "com.imyeyu.gao.customer";
/**
* 服务端下发的更新信息
*
- * 在插件协议基础上多三个字段,插件不识别但会原样透传:
+ * 在插件协议基础上增加更新说明与外壳字段,插件会原样透传:
* note 是更新说明,shell 标记产物为安装包(外壳),mandatory 标记强制更新
*/
export type UpdateInfo = LatestVersion & {
note?: string;
shell?: boolean;
mandatory?: boolean;
+ shellUrl?: string;
+ shellVersion?: string;
+ shellChecksum?: string;
+ shellMandatory?: boolean;
};
// 模块级状态,页面与启动逻辑共享同一份
@@ -57,9 +61,18 @@ async function check(): Promise {
checking.value = true;
error.value = "";
try {
- const result = await CapacitorUpdater.getLatest();
- latest.value = result;
- return result;
+ const result: UpdateInfo = await CapacitorUpdater.getLatest();
+ // 新协议的独立外壳地址优先,统一转换为页面已有的外壳更新格式
+ const target: UpdateInfo = result.shellUrl ? {
+ ...result,
+ url: result.shellUrl,
+ version: result.shellVersion ?? result.version,
+ checksum: result.shellChecksum,
+ mandatory: result.shellMandatory,
+ shell: true
+ } : result;
+ latest.value = target;
+ return target;
} catch (e) {
error.value = e instanceof Error ? e.message : "检查更新失败";
return null;
@@ -141,7 +154,11 @@ async function apply(bundle: BundleInfo): Promise {
} catch (e) {
// 包目录已被清理或本身就是坏的(例如把安装包当热更包下下来),
// set 会报 id 不存在。不清理的话每次启动都卡在「已下载,重启生效」
- await CapacitorUpdater.delete({ id: bundle.id }).catch(() => undefined);
+ try {
+ await CapacitorUpdater.delete({ id: bundle.id });
+ } catch {
+ // 包可能已经被插件清理
+ }
ready.value = null;
error.value = e instanceof Error ? e.message : "更新失败";
}
@@ -231,27 +248,6 @@ function promptUpdate(bundle: BundleInfo): void {
});
}
-/**
- * 弹窗引导下载安装包
- *
- * 外壳更新装不进热更,只能走浏览器下载后覆盖安装;强制更新不给「稍后」按钮
- */
-function promptShellUpdate(info: UpdateInfo): void {
- const dialog = DialogPlugin.confirm({
- title: "需要安装新版本",
- content: `v${info.version} 是应用外壳更新,需要下载安装包覆盖安装`,
- cancelBtn: info.mandatory ? null : "稍后",
- confirmBtn: "下载安装包",
- onCancel() {
- dialog.destroy();
- },
- onConfirm() {
- dialog.destroy();
- openShellDownload();
- }
- });
-}
-
/**
* 启动时检查更新
*
@@ -272,11 +268,11 @@ export async function runAutoUpdate(): Promise {
return;
}
const result = await check();
- if (!result?.url) {
+ // 外壳更新不弹窗,入口统一在「版本更新」页
+ if (result?.shell) {
return;
}
- if (result.shell) {
- promptShellUpdate(result);
+ if (!result?.url) {
return;
}
if (result.version === currentVersion.value || !isAutoUpdateEnabled()) {
diff --git a/src/composables/useShellUpdate.ts b/src/composables/useShellUpdate.ts
new file mode 100644
index 0000000..f391d0c
--- /dev/null
+++ b/src/composables/useShellUpdate.ts
@@ -0,0 +1,132 @@
+import { Capacitor, registerPlugin, type PluginListenerHandle } from "@capacitor/core";
+import { DialogPlugin } from "tdesign-mobile-vue";
+import type { Ref } from "vue";
+import type { UpdateInfo } from "@/composables/useAppUpdate";
+
+interface ShellUpdaterPlugin {
+ canInstall(): Promise<{ allowed: boolean }>;
+ openInstallSettings(): Promise;
+ downloadAndInstall(options: { url: string; sha256: string; fileName: string }): Promise;
+ addListener(eventName: "downloadProgress", listener: (progress: { percent: number; received: number; total: number }) => void): Promise;
+ addListener(eventName: "resume", listener: () => void): Promise;
+}
+
+const ShellUpdater = registerPlugin("ShellUpdater");
+
+/** 管理更新页的外壳安装和授权流程 */
+export function useShellUpdate(latest: Ref) {
+ const downloading = ref(false);
+ const percent = ref(0);
+ const error = ref("");
+ let waitingForSettings = false;
+ let resumeListener: PluginListenerHandle | undefined;
+ let disposed = false;
+
+ /** 下载并交给系统安装器 */
+ async function install(): Promise {
+ const target = latest.value;
+ if (!target?.url || !target.checksum) {
+ error.value = "缺少安装包地址或校验值";
+ return;
+ }
+ downloading.value = true;
+ percent.value = 0;
+ error.value = "";
+ let listener: PluginListenerHandle | undefined;
+ try {
+ listener = await ShellUpdater.addListener("downloadProgress", progress => {
+ percent.value = progress.percent;
+ });
+ await ShellUpdater.downloadAndInstall({
+ url: target.url,
+ sha256: target.checksum,
+ fileName: `app-${target.version}.apk`
+ });
+ } catch (e) {
+ error.value = e instanceof Error ? e.message : "安装包下载失败";
+ } finally {
+ if (listener) {
+ await listener.remove();
+ }
+ downloading.value = false;
+ }
+ }
+
+ /** 从授权页返回后只检查一次 */
+ async function handleResume(): Promise {
+ if (!waitingForSettings) {
+ return;
+ }
+ waitingForSettings = false;
+ try {
+ const result = await ShellUpdater.canInstall();
+ if (result.allowed) {
+ await install();
+ } else {
+ error.value = "未获得安装权限,可重试或使用浏览器下载";
+ }
+ } catch (e) {
+ error.value = e instanceof Error ? e.message : "检查安装权限失败";
+ }
+ }
+
+ /** 检查权限,旧壳交给浏览器下载 */
+ async function start(): Promise {
+ error.value = "";
+ if (!Capacitor.isPluginAvailable("ShellUpdater")) {
+ if (latest.value?.url) {
+ window.location.assign(latest.value.url);
+ }
+ return;
+ }
+ try {
+ const result = await ShellUpdater.canInstall();
+ if (result.allowed) {
+ await install();
+ return;
+ }
+ const dialog = DialogPlugin.confirm({
+ title: "需要安装权限",
+ content: "请允许此应用安装未知应用,返回后将继续下载并安装。",
+ cancelBtn: "稍后",
+ confirmBtn: "去设置",
+ onCancel() {
+ dialog.destroy();
+ },
+ async onConfirm() {
+ dialog.destroy();
+ waitingForSettings = true;
+ try {
+ await ShellUpdater.openInstallSettings();
+ } catch (e) {
+ waitingForSettings = false;
+ error.value = e instanceof Error ? e.message : "无法打开安装权限设置";
+ }
+ }
+ });
+ } catch (e) {
+ error.value = e instanceof Error ? e.message : "检查安装权限失败";
+ }
+ }
+
+ onMounted(async () => {
+ if (!Capacitor.isPluginAvailable("ShellUpdater")) {
+ return;
+ }
+ const listener = await ShellUpdater.addListener("resume", () => { void handleResume(); });
+ if (disposed) {
+ await listener.remove();
+ } else {
+ resumeListener = listener;
+ }
+ });
+ onUnmounted(async () => {
+ disposed = true;
+ waitingForSettings = false;
+ if (resumeListener) {
+ await resumeListener.remove();
+ }
+ });
+
+ return { downloading, percent, error, start };
+}
diff --git a/src/pages/setting/AppUpdate.vue b/src/pages/setting/AppUpdate.vue
index 4daa4e0..a9a9efc 100644
--- a/src/pages/setting/AppUpdate.vue
+++ b/src/pages/setting/AppUpdate.vue
@@ -33,6 +33,11 @@
>
检查更新
+
+
+ 重试
+ 用浏览器下载
+
-
+
(
() => (currentVersion.value && currentVersion.value !== "builtin" ? currentVersion.value : version)
@@ -168,13 +176,13 @@ const displayVersion = computed(
const latestVersionText = computed(() => (hasUpdate() ? `v${latest.value?.version ?? ""}` : ""));
/** 当前所处的更新阶段 */
-const updateStage = computed<"check" | "shell" | "download" | "downloading" | "apply">(() => {
- if (isShellUpdate()) {
- return "shell";
- }
- if (downloading.value) {
+const updateStage = computed<"check" | "shell" | "shell-error" | "download" | "downloading" | "apply">(() => {
+ if (downloading.value || shellDownloading.value) {
return "downloading";
}
+ if (isShellUpdate()) {
+ return shellError.value ? "shell-error" : "shell";
+ }
if (ready.value) {
return "apply";
}
@@ -259,9 +267,9 @@ async function handleCheck(): Promise {
await loadNotes();
}
-/** 外壳更新:交给系统浏览器下载安装包 */
-function handleShellDownload(): void {
- openShellDownload();
+/** 外壳更新:优先使用原生安装能力 */
+async function handleShellDownload(): Promise {
+ await startShellUpdate();
}
async function handleDownload(): Promise {
diff --git a/src/pages/tabs/component/PendingNoticeBar.vue b/src/pages/tabs/component/PendingNoticeBar.vue
index d0e8df6..d2a1a83 100644
--- a/src/pages/tabs/component/PendingNoticeBar.vue
+++ b/src/pages/tabs/component/PendingNoticeBar.vue
@@ -23,11 +23,21 @@ import { usePendingNoticeStore } from "@/store/pendingNoticeStore";
const pendingNoticeStore = usePendingNoticeStore();
const router = useRouter();
-const { supported, latest, autoUpdate, hasUpdate } = useAppUpdate();
+const { supported, latest, autoUpdate, hasUpdate, isShellUpdate } = useAppUpdate();
const noticeList = computed(() => {
const notices = [...pendingNoticeStore.pendingNoticeList];
- if (supported && !autoUpdate.value && hasUpdate() && latest.value) {
- notices.push({ content: `有可用新版本 v${latest.value.version} 更新`, name: "AppUpdate", query: {} });
+ if (supported && hasUpdate() && latest.value) {
+ // 外壳更新不会自动下载,自动更新开着也必须提示;热更开着开关就不提示了
+ const shell = isShellUpdate();
+ if (shell || !autoUpdate.value) {
+ notices.push({
+ content: shell
+ ? `需要安装新版本 v${latest.value.version},点击前往更新`
+ : `有可用新版本 v${latest.value.version} 更新`,
+ name: "AppUpdate",
+ query: {}
+ });
+ }
}
return notices;
});