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.
This commit is contained in:
@@ -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<void> {
|
||||
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<void> {
|
||||
} catch (error) {
|
||||
console.error('Install APK error:', error);
|
||||
// 尝试使用浏览器下载
|
||||
const webUrl = apkUri.replace('file://', '');
|
||||
Linking.openURL(webUrl);
|
||||
Linking.openURL(apkUri.replace('file://', ''));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user