88 lines
2.2 KiB
TypeScript
88 lines
2.2 KiB
TypeScript
import * as Sentry from '@sentry/react-native'
|
||
import * as Updates from 'expo-updates'
|
||
import { useEffect, useState } from 'react'
|
||
|
||
interface UseUpdateCheckerOptions {
|
||
/** 检查更新的间隔时间(毫秒),默认1分钟 */
|
||
interval?: number
|
||
/** 是否启用定时检查,默认true */
|
||
enablePeriodicCheck?: boolean
|
||
}
|
||
|
||
export const useUpdateChecker = ({
|
||
interval = 5 * 60 * 1000, // 5分钟
|
||
enablePeriodicCheck = true,
|
||
}: UseUpdateCheckerOptions = {}) => {
|
||
const [hasUpdate, setHasUpdate] = useState(false)
|
||
const [isChecking, setIsChecking] = useState(false)
|
||
const [checkError, setCheckError] = useState<string | null>(null)
|
||
const checkForUpdates = async () => {
|
||
// 只在非开发环境下检查更新
|
||
if (__DEV__ || !Updates.isEnabled) {
|
||
return false
|
||
}
|
||
|
||
try {
|
||
setIsChecking(true)
|
||
setCheckError(null)
|
||
|
||
// 检查是否有更新可用
|
||
const update = await Updates.checkForUpdateAsync()
|
||
|
||
console.log('update-------', update)
|
||
|
||
Sentry.captureMessage('useUpdateChecker', {
|
||
tags: {
|
||
useUpdateChecker: 'checkForUpdateAsync',
|
||
component: 'useUpdateChecker',
|
||
},
|
||
contexts: {
|
||
update: update,
|
||
},
|
||
})
|
||
|
||
if (update.isAvailable) {
|
||
setHasUpdate(true)
|
||
return true
|
||
} else {
|
||
setHasUpdate(false)
|
||
return false
|
||
}
|
||
} catch (error) {
|
||
console.error('检查更新失败:', error)
|
||
setCheckError(error instanceof Error ? error.message : '检查更新失败')
|
||
setHasUpdate(false)
|
||
|
||
Sentry.captureMessage('useUpdateCheckerError', {
|
||
tags: {
|
||
useUpdateChecker: 'checkForUpdateAsync_failed',
|
||
component: 'useUpdateChecker',
|
||
},
|
||
contexts: {
|
||
update: {
|
||
isEnabled: Updates.isEnabled,
|
||
__DEV__: __DEV__,
|
||
},
|
||
},
|
||
})
|
||
return false
|
||
} finally {
|
||
setIsChecking(false)
|
||
}
|
||
}
|
||
|
||
useEffect(() => {
|
||
checkForUpdates()
|
||
}, [])
|
||
|
||
// 使用 useInterval 进行定时检查
|
||
const updateTimer = setInterval(checkForUpdates, enablePeriodicCheck ? interval : undefined)
|
||
|
||
return {
|
||
hasUpdate,
|
||
isChecking,
|
||
checkError,
|
||
checkForUpdates,
|
||
}
|
||
}
|