Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions native-modules/react-native-device-utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ ReactNativeDeviceUtils.initEventListeners();
const { launchType, deepLink } =
await ReactNativeDeviceUtils.getLaunchOptions();
const startupTime = await ReactNativeDeviceUtils.getStartupTime();
const isFirstLaunch = ReactNativeDeviceUtils.isFirstLaunch();
const isFirstAppVersionLaunch = ReactNativeDeviceUtils.isFirstLaunchForCurrentAppVersion();
if (process.env.BUNDLE_VERSION) {
Comment thread
huhuanming marked this conversation as resolved.
Resolved
ReactNativeDeviceUtils.initFirstLaunchForBundle(process.env.BUNDLE_VERSION);
}
const isFirstBundleLaunch = ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle();

// Claim a startup stage exactly once across runtimes.
const claimed = ReactNativeDeviceUtils.setInMemoryValueIfAbsent(
Expand All @@ -74,13 +80,63 @@ const claimed = ReactNativeDeviceUtils.setInMemoryValueIfAbsent(
Consumers own key namespaces and decide what to do with each result. Store
values are native copies, not retained JS objects.

### First launch in shared code

The following entry point works in React Native, Web, Electron renderers,
and extension pages. Call `initFirstLaunch` once at app startup, then read
the cached booleans synchronously anywhere:

```ts
import {
initFirstLaunch,
isFirstLaunch,
isFirstLaunchForCurrentAppVersion,
isFirstLaunchForCurrentBundle,
resetFirstLaunch,
} from '@onekeyfe/react-native-device-utils/first-launch';

// Call once at app startup. On Web/Desktop/Extension, pass host-sampled
// `isLegacyInstall` / `legacyAppVersion` if upgrading from versions before this API.
initFirstLaunch({
appVersion,
bundleVersion,
isLegacyInstall,
});

// Pure in-memory reads during the current launch.
const firstLaunch = isFirstLaunch();
const firstAppVersionLaunch = isFirstLaunchForCurrentAppVersion();
const firstBundleLaunch = isFirstLaunchForCurrentBundle();

// Optional: clear persisted files/keys AND in-memory cache (e.g. on Reset App before JS restart).
resetFirstLaunch();
```

On iOS and Android, initialize the pure native singleton early in
`AppDelegate.didFinishLaunchingWithOptions` (`OneKeyDeviceUtilsFirstLaunch` via
`initializeWithOptions:` / `hasPersistedStateNumber`) or `Application.onCreate()`
(`DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... })`) so
host-specific legacy upgrade detection stays in the app and runs before React Native starts.

Persisted state is stored as 3 independent plain-text entries (`launched`,
`app_ver`, `bundle_ver` under `1k_first_launch/` on native; `1k_fl_launched`,
`1k_fl_app_ver`, `1k_fl_bundle_ver` in `localStorage` on Web/Desktop/Extension),
so storage never grows and requires no cleanup. Rolling back to a version lower
than the recorded highest version returns `false`. Call from an extension-owned
UI page; an MV3 service worker returns `false`.

## API

| Method | Result | Platforms | Description |
| --- | --- | :-: | --- |
| `initEventListeners()` | `void` | iOS, Android | Registers native listeners; call once at startup. |
| `getLaunchOptions()` / `clearLaunchOptions()` | `Promise<LaunchOptions>` / `Promise<boolean>` | iOS, Android | Read or consume the app's launch type and optional deep link. |
| `getStartupTime()` | `Promise<number>` | iOS, Android | Native startup timestamp. |
| `isFirstLaunch()` | `boolean` | iOS, Android | Synchronous first launch of the local installation, with a stable result for the native process. |
| `isFirstLaunchForCurrentAppVersion()` | `boolean` | iOS, Android | First launch of a native release version higher than any previously launched version. |
| `initFirstLaunchForBundle(bundleVersion)` | `void` | iOS, Android | Records the executing bundle at JS startup / OTA reload as the active bundle identity. |
| `isFirstLaunchForCurrentBundle(bundleVersion?)` | `boolean` | iOS, Android | First launch of a bundle version higher than any previously launched bundle. |
| `resetFirstLaunch()` | `boolean` | iOS, Android | Clears persisted `1k_first_launch/` files and in-memory launch state; returns `false` if deletion fails. |
| `getDeviceToken()` / `saveDeviceToken(token)` / `registerDeviceToken()` | `Promise<string>` / `Promise<void>` / `Promise<boolean>` | iOS, Android | Push-token plumbing; host setup still owns registration. |
| `getInMemoryValue(key)` / `setInMemoryValue(key, value)` / `removeInMemoryValue(key)` / `setInMemoryValueIfAbsent(key, value)` | `InMemoryValue \| undefined` / `void` / `boolean` / `boolean` | iOS, Android | Synchronous bounded primitive store. |
| `getAndClearColdStartLocalNotification()` | `Promise<string>` | iOS, Android | Returns local-notification JSON once; Android returns `""`. |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package com.margelo.nitro.reactnativedeviceutils

import android.content.Context
import android.content.pm.PackageManager
import java.io.File

/**
* Pure native process-wide singleton for first-launch tracking.
* Has no Nitro/JSI dependencies, so host apps can initialize it early in
* `Application.onCreate()` before React Native starts.
*/
object DeviceUtilsFirstLaunch {
private val lock = Any()

@Volatile
private var history: FirstLaunchHistory? = null

private fun baseDirectory(context: Context): File? {
val appContext = context.applicationContext ?: context
return appContext.noBackupFilesDir
}

/**
* Returns true if the persisted launched marker already exists on disk.
*/
@JvmStatic
fun hasPersistedState(context: Context): Boolean {
val base = baseDirectory(context) ?: return false
return File(File(base, FirstLaunchHistory.DIRECTORY_NAME), FirstLaunchHistory.LAUNCHED_FILE_NAME).exists()
}

/**
* Initializes the process-wide first-launch state. Subsequent calls are no-ops.
*/
@JvmStatic
@JvmOverloads
fun initialize(
context: Context,
isLegacyInstall: Boolean = false,
legacyAppVersion: String? = null,
) {
initialize(
context = context,
isLegacyInstall = { isLegacyInstall },
legacyAppVersion = { legacyAppVersion },
)
}

/**
* Kotlin-friendly initializer whose legacy-detection lambdas are only evaluated
* when no persisted launched marker exists yet.
*/
fun initialize(
context: Context,
isLegacyInstall: () -> Boolean,
legacyAppVersion: () -> String? = { null },
) {
if (history != null) return
synchronized(lock) {
if (history != null) return
val appContext = context.applicationContext ?: context
val base = baseDirectory(appContext) ?: return
val versionName = try {
@Suppress("DEPRECATION")
appContext.packageManager.getPackageInfo(appContext.packageName, 0).versionName
} catch (_: PackageManager.NameNotFoundException) {
null
} catch (_: SecurityException) {
null
}
val persistedExists =
File(File(base, FirstLaunchHistory.DIRECTORY_NAME), FirstLaunchHistory.LAUNCHED_FILE_NAME).exists()
val hasPreviousLaunch = if (persistedExists) false else runCatching(isLegacyInstall).getOrDefault(false)
val previousVersion = if (persistedExists) null else runCatching(legacyAppVersion).getOrNull()
history = FirstLaunchHistory(
baseDirectory = base,
appVersion = versionName,
previousAppVersion = previousVersion,
hasPreviousLaunch = hasPreviousLaunch,
)
}
}

/**
* Deletes persisted first-launch files and clears in-memory state so a subsequent
* JS restart within the same native process observes a fresh launch.
* Returns true if persisted files were removed (or already absent), false on failure.
*/
@JvmStatic
fun reset(context: Context): Boolean {
synchronized(lock) {
Comment thread
huhuanming marked this conversation as resolved.
Resolved
val base = baseDirectory(context) ?: return false
val storeDir = File(base, FirstLaunchHistory.DIRECTORY_NAME)
if (storeDir.exists()) {
val deleted = try {
storeDir.deleteRecursively() && !storeDir.exists()
} catch (_: SecurityException) {
false
}
if (!deleted) {
return false
}
}
history = null
return true
}
}

internal fun isFirstLaunch(fallbackContext: Context? = null): Boolean = synchronized(lock) {
ensureInitializedLocked(fallbackContext)
history?.isFirstLaunch ?: false
}

internal fun isFirstLaunchForCurrentAppVersion(fallbackContext: Context? = null): Boolean = synchronized(lock) {
ensureInitializedLocked(fallbackContext)
history?.isFirstLaunchForCurrentAppVersion ?: false
}

internal fun initForBundle(
bundleVersion: String,
fallbackContext: Context? = null,
) = synchronized(lock) {
ensureInitializedLocked(fallbackContext)
history?.initForBundle(bundleVersion)
}

internal fun isFirstLaunchForBundle(
bundleVersion: String?,
fallbackContext: Context? = null,
): Boolean = synchronized(lock) {
ensureInitializedLocked(fallbackContext)
history?.isFirstLaunchForBundle(bundleVersion) ?: false
}

private fun ensureInitializedLocked(fallbackContext: Context?) {
if (history == null && fallbackContext != null) {
initialize(fallbackContext)
}
}
}
Loading
Loading