From d280ad1656e91772eef2fe20bf6507a171687867 Mon Sep 17 00:00:00 2001 From: lafay <2021211506@stu.hit.edu.cn> Date: Thu, 26 Mar 2026 03:45:39 +0800 Subject: [PATCH] feat(APKUpdate): conditionally import native modules for APK updates on Android - Implemented conditional imports for `expo-file-system` and `expo-intent-launcher` to ensure compatibility with non-Android environments. - Added error handling to alert users when native modules are unavailable, directing them to download APKs via the browser. - Enhanced the `installAPK` function to check for the availability of native modules before proceeding with installation. --- src/services/apkUpdateService.ts | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/services/apkUpdateService.ts b/src/services/apkUpdateService.ts index 6d2de6d..55ba1db 100644 --- a/src/services/apkUpdateService.ts +++ b/src/services/apkUpdateService.ts @@ -5,11 +5,22 @@ import { Platform, Linking, Alert } from 'react-native'; import Constants from 'expo-constants'; -import * as FileSystem from 'expo-file-system/legacy'; -import * as IntentLauncher from 'expo-intent-launcher'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { showConfirm } from './dialogService'; +// 条件导入原生模块(仅在 Android 上可用) +let FileSystem: typeof import('expo-file-system/legacy') | null = null; +let IntentLauncher: typeof import('expo-intent-launcher') | null = null; + +if (Platform.OS === 'android') { + try { + FileSystem = require('expo-file-system/legacy'); + IntentLauncher = require('expo-intent-launcher'); + } catch (e) { + console.warn('Failed to load native modules for APK update:', e); + } +} + // 更新服务器地址 const UPDATES_SERVER_URL = Constants.expoConfig?.extra?.updatesUrl ? Constants.expoConfig.extra.updatesUrl.replace('/api/manifest', '') @@ -133,6 +144,12 @@ async function downloadAndInstallAPK(downloadUrl: string, version: string): Prom return; } + if (!FileSystem) { + Alert.alert('提示', '当前环境不支持 APK 更新,请在浏览器中下载'); + Linking.openURL(downloadUrl); + return; + } + try { const downloadPath = `${FileSystem.documentDirectory}carrot-bbs-${version}.apk`; @@ -171,6 +188,10 @@ async function downloadAndInstallAPK(downloadUrl: string, version: string): Prom */ async function installAPK(apkUri: string): Promise { try { + if (!FileSystem || !IntentLauncher) { + throw new Error('Native modules not available'); + } + // 获取文件的 content URI const contentUri = await FileSystem.getContentUriAsync(apkUri); @@ -182,8 +203,7 @@ async function installAPK(apkUri: string): Promise { } catch (error) { console.error('Install APK error:', error); // 尝试使用浏览器下载 - const webUrl = apkUri.replace('file://', ''); - Linking.openURL(webUrl); + Linking.openURL(apkUri.replace('file://', '')); } }