### startService(context: Context, guid: String? = null) Source: https://github.com/2dust/v2rayng Starts the core service with an optional server GUID. If a GUID is provided, it first sets the selected server via MmkvManager.setSelectServer(guid). Throws are caught, logged, and toasted. ```APIDOC ## startService(context: Context, guid: String? = null) ### Description Starts the core service with an optional server GUID. If a GUID is provided, it first sets the selected server via MmkvManager.setSelectServer(guid). Throws are caught, logged, and toasted. ### Method Function call ### Parameters - **context** (Context) - Required - Android context - **guid** (String?) - Optional (default: null) - When non-null, first calls MmkvManager.setSelectServer(guid) ### Example ```kotlin try { LauncherManager.startService(context, guid = selectedGuid) } catch (e: IllegalStateException) { // invalid selection / missing permission — message already shown by start's own toast } ``` ``` -------------------------------- ### Example — start with explicit selection Source: https://github.com/2dust/v2rayng Shows how to call LauncherManager.startService with a specific guid and catch IllegalStateException for invalid selection or missing permission; the message is already shown by start's own toast. ```kotlin try { LauncherManager.startService(context, guid = selectedGuid) } catch (e: IllegalStateException) { // invalid selection / missing permission — message already shown by start's own toast } ``` -------------------------------- ### startService method signature Source: https://github.com/2dust/v2rayng Starts the service. When guid is non-null, first calls MmkvManager.setSelectServer(guid). Throws are caught, logged, and toasted (message or exception class name). ```kotlin fun startService(context: Context, guid: String? = null) ``` -------------------------------- ### Usage example for profile lookup Source: https://github.com/2dust/v2rayng Shows how to resolve a routing target by name and get remarks for pickers. ```kotlin val entry = SettingsManager.getProfileEntryViaRemarks("routing-tag-name") ?: return val ids = SettingsManager.getProfileRemarks() // for pickers ``` -------------------------------- ### Encrypted backup round trip example Source: https://github.com/2dust/v2rayng Complete usage example: configure WebDavConfig, init manager, upload backup_ng.zip, then download and unzip. No exceptions are thrown; check return values. ```kotlin val config = WebDavConfig( baseUrl = "https://dav.example.com/remote.php/dav", username = "me@example.com", password = "app-password", remoteBasePath = "backups", timeoutSeconds = 30, ) WebDavManager.init(config) val backup = File(context.cacheDir, "backup_ng.zip") if (WebDavManager.uploadFile(backup, "backup_ng.zip")) { LogUtil.i(TAG, "backup uploaded") } else { LogUtil.e(TAG, "backup upload failed — no exception is thrown, check return value") } if (WebDavManager.downloadFile("backup_ng.zip", restoreTarget)) { ZipUtil.unzipToFolder(restoreTarget, destDir) } ``` -------------------------------- ### Example usage of encodeServerConfig and decodeServerConfig Source: https://github.com/2dust/v2rayng Shows encoding a parsed Vmess link with a blank GUID (generates a new UUID) and then decoding it back. The returned GUID is the effective key used for storage. ```kotlin val guid = MmkvManager.encodeServerConfig("", VmessFmt.parse(link)!!) val reloaded: ProfileItem? = MmkvManager.decodeServerConfig(guid) ``` -------------------------------- ### startServiceFromToggle(context: Context): Boolean Source: https://github.com/2dust/v2rayng Starts the core service from a UI toggle (quick-settings tile or widget). Returns false with a first-use toast when no server is selected, or when the service start throws (toast shows the error); otherwise returns true. ```APIDOC ## startServiceFromToggle(context: Context): Boolean ### Description Starts the core service from a UI toggle (quick-settings tile or widget). Returns false with a first-use toast when no server is selected, or when the service start throws (toast shows the error); otherwise returns true. ### Method Function call ### Parameters - **context** (Context) - Required - UI or widget context ### Returns - **Boolean** - `false` (with a first-use toast) when no server is selected; `false` when the service start throws (toast shows the error); otherwise `true`. ``` -------------------------------- ### Example: simple-obfs http plugin Source: https://github.com/2dust/v2rayng Example SIP002 link with the obfs=http plugin option. The plugin query parameter sets network=TCP, headerType="http", and reads obfs-host/path from the plugin's ;-separated pairs. ```plaintext ss://YWVzLTI1Ni1nY206cGFzcw@host:8388/?plugin=obfs%3Dhttp%3Bobfs-host%3Dbing.com ``` -------------------------------- ### initCoreEnv usage example Source: https://github.com/2dust/v2rayng Calls initCoreEnv inside a try-catch. On failure, logs the error and retries on next start. ```kotlin try { CoreNativeManager.initCoreEnv(context) } catch (e: Exception) { LogUtil.e(TAG, "Core init failed, will retry on next start", e) } ``` -------------------------------- ### toUri example usage Source: https://github.com/2dust/v2rayng Example of calling toUri via VlessFmt, which delegates to FmtBase.toUri with password and query dictionary. ```kotlin val profile = MmkvManager.decodeServerConfig(guid)!! val link = VlessFmt.toUri(profile) // delegates to FmtBase.toUri(config, password, queryDic) ``` -------------------------------- ### Example — share a profile Source: https://github.com/2dust/v2rayng Shows how to generate a share link by prepending the protocol scheme to the result of toUri and copying it to the clipboard. ```kotlin val config = MmkvManager.decodeServerConfig(guid)!! val share = EConfigType.VMESS.protocolScheme + VmessFmt.toUri(config) Utils.setClipboard(context, share) ``` -------------------------------- ### Example: retrieving ports and credentials Source: https://github.com/2dust/v2rayng Shows how to obtain the SOCKS and HTTP ports and optional credentials. The credentials are null when either username or password preference is empty. ```kotlin val socksPort = SettingsManager.getSocksPort() val httpPort = SettingsManager.getHttpPort() val credentials = SettingsManager.getSocksUsername()?.let { user -> SettingsManager.getSocksPassword()?.let { pass -> user to pass } } ``` -------------------------------- ### parse usage example Source: https://github.com/2dust/v2rayng Shows how to call parse with sample header values. The comment indicates the expected parsed fields. ```kotlin val info = SubscriptionInfoParser.parse( userInfo = "upload=1048576; download=2097152; total=1073741824; expire=1700000000", profileTitle = "My Panel", supportUrl = "https://t.me/mychannel", webPageUrl = null, ) // info.upload == 1048576, info.total == 1073741824, info.title == "My Panel" ``` -------------------------------- ### SocksFmt.toUri share example Source: https://github.com/2dust/v2rayng Builds a socks5:// link from a stored config and copies it to the clipboard. ```kotlin val config = MmkvManager.decodeServerConfig(guid)!! val link = AppConfig.SOCKS5 + SocksFmt.toUri(config) // "socks5://" + ... Utils.setClipboard(context, link) ``` -------------------------------- ### Example: share as SIP002 Source: https://github.com/2dust/v2rayng Shows how to generate a share link from a stored server config and copy it to the clipboard. The resulting link is ss://base64(method:password)@host:port#remarks. ```kotlin val config = MmkvManager.decodeServerConfig(guid)!! val link = EConfigType.SHADOWSOCKS.protocolScheme + ShadowsocksFmt.toUri(config) Utils.setClipboard(context, link) // ss://base64(method:password)@host:port#remarks ``` -------------------------------- ### encodeServerConfig(guid: String, config: ProfileItem): String Source: https://github.com/2dust/v2rayng Encodes and stores the profile configuration for a server. Returns the GUID. ```APIDOC ## encodeServerConfig(guid: String, config: ProfileItem): String ### Description Encodes and stores the profile configuration for a server. Returns the GUID. ### Method encodeServerConfig ### Parameters - **guid** (String) - Required - The server GUID. - **config** (ProfileItem) - Required - The profile configuration to store. ### Response - **String** - The GUID of the stored server. ``` -------------------------------- ### Example: legacy parse with error handling Source: https://github.com/2dust/v2rayng Shows how to parse a legacy link and handle a null result. Uses Utils.encode to build the base64 user-info and LogUtil to log success or failure. ```kotlin val link = "ss://" + Utils.encode("aes-256-gcm:secret@1.2.3.4:8388") + "#Work" val profile = ShadowsocksFmt.parse(link) if (profile == null) LogUtil.w(TAG, "not a valid ss link") else LogUtil.d(TAG, "${profile.method} @ ${profile.server}:${profile.serverPort}") ``` -------------------------------- ### decodeServerConfig(guid: String): ProfileItem? Source: https://github.com/2dust/v2rayng Decodes the profile configuration for a given server GUID. Returns null if not found. ```APIDOC ## decodeServerConfig(guid: String): ProfileItem? ### Description Decodes the profile configuration for a given server GUID. Returns null if not found. ### Method decodeServerConfig ### Parameters - **guid** (String) - Required - The server GUID. ### Response - **ProfileItem?** - The profile configuration, or null if not found. ``` -------------------------------- ### Settings round trip example Source: https://github.com/2dust/v2rayng Encodes a SOCKS port setting and then decodes it back using the same key and a default fallback. Demonstrates the typical encode/decode pattern for settings. ```kotlin MmkvManager.encodeSettings(AppConfig.PREF_SOCKS_PORT, "10808") val port = MmkvManager.decodeSettingsString(AppConfig.PREF_SOCKS_PORT, AppConfig.PORT_SOCKS) ``` -------------------------------- ### toUri example for sharing Source: https://github.com/2dust/v2rayng Builds a share link by decoding a server config and prepending the trojan:// scheme to the serialized URI. ```kotlin val config = MmkvManager.decodeServerConfig(guid)!! val link = EConfigType.TROJAN.protocolScheme + TrojanFmt.toUri(config) ``` -------------------------------- ### startServiceFromToggle method signature Source: https://github.com/2dust/v2rayng Returns false with a first-use toast when no server is selected, false when service start throws (toast shows error), otherwise true. Used by quick-settings tile and widget click path. ```kotlin fun startServiceFromToggle(context: Context): Boolean ``` -------------------------------- ### parse example with wireguard:// URI Source: https://github.com/2dust/v2rayng Shows parsing a wireguard:// link with query parameters. The resulting profile fields are set as shown in the comment. ```kotlin val profile = WireguardFmt.parse( "wireguard://privkey@1.2.3.4:51820?publickey=pub&address=172.16.0.2%2F32&reserved=1,2,3&mtu=1420#WG" ) // profile.secretKey == "privkey", profile.publicKey == "pub", profile.reserved == "1,2,3" ``` -------------------------------- ### Example: importing a paste from the user Source: https://github.com/2dust/v2rayng Shows how to call importBatchConfig with a multi-line server string, the default subscription ID, and append=true. The result is a Pair; if either count is greater than zero, showSuccess() is called. ```kotlin val (configs, subs) = AngConfigManager.importBatchConfig( server = "vmess://...\nvless://...\nss://...", subid = MmkvManager.DEFAULT_SUBSCRIPTION_ID, append = true, ) if (configs > 0 || subs > 0) showSuccess() ``` -------------------------------- ### getSelectServer(): String? Source: https://github.com/2dust/v2rayng Retrieves the GUID of the currently selected server. Returns null if no server is selected. ```APIDOC ## getSelectServer(): String? ### Description Retrieves the GUID of the currently selected server. Returns null if no server is selected. ### Method getSelectServer ### Parameters None ### Response - **String?** - The GUID of the selected server, or null if none. ``` -------------------------------- ### toUri example with optional fields Source: https://github.com/2dust/v2rayng Builds a full wireguard:// link from a stored profile using the protocol scheme and toUri. ```kotlin val config = MmkvManager.decodeServerConfig(guid)!! val link = EConfigType.WIREGUARD.protocolScheme + WireguardFmt.toUri(config) ``` -------------------------------- ### SocksFmt.parse example with credentials Source: https://github.com/2dust/v2rayng Parses a socks:// URI with user:pass credentials. The fragment becomes remarks, and user-info is split on the first colon. ```kotlin val profile = SocksFmt.parse("socks://user:pass@1.2.3.4:1080#MySocks") // profile.username == "user", profile.password == "pass", // profile.server == "1.2.3.4", profile.serverPort == "1080" ``` -------------------------------- ### Example — import a legacy VMess link Source: https://github.com/2dust/v2rayng Shows how to parse a legacy base64 VMess link. The link is built with Utils.encode and the resulting ProfileItem has configType VMESS with fields like server, serverPort, password, network, security, and sni. ```kotlin val link = "vmess://" + Utils.encode( """{"add":"1.2.3.4","port":"443","id":"uuid-here","net":"ws","ps":"MyServer","tls":"tls","sni":"cdn.example.com"}""" ) val profile = VmessFmt.parse(link) // -> ProfileItem(configType=VMESS, server="1.2.3.4", serverPort="443", // password="uuid-here", network="ws", security="tls", sni="cdn.example.com") ``` -------------------------------- ### isXray() Source: https://github.com/2dust/v2rayng Checks if the application ID starts with 'com.v2ray.ang'. ```APIDOC ## isXray() ### Description Checks if the application ID starts with 'com.v2ray.ang'. ### Method Function ### Returns - **Boolean** - True if the application ID starts with 'com.v2ray.ang'. ``` -------------------------------- ### Round trip example Source: https://github.com/2dust/v2rayng Shows a round trip from config to URI and back, verifying obfs-password is preserved. ```kotlin val config = MmkvManager.decodeServerConfig(guid)!! val link = EConfigType.HYSTERIA2.protocolScheme + Hysteria2Fmt.toUri(config) val back = Hysteria2Fmt.parse(link) check(back.obfsPassword == config.obfsPassword) { "round trip lost obfs-password" } ``` -------------------------------- ### Round trip example Source: https://github.com/2dust/v2rayng Shows converting a stored config to a link and back to verify round trip. ```kotlin val config = MmkvManager.decodeServerConfig(guid)!! val link = EConfigType.MASQUE.protocolScheme + MasqueFmt.toUri(config) val back = MasqueFmt.parse(link) ?: error("masque round trip failed") ``` -------------------------------- ### shareFullContent2Clipboard Source: https://github.com/2dust/v2rayng Builds the full runtime configuration via CoreConfigManager.getV2rayConfig and copies the pretty JSON to the clipboard. Returns 0 on success, -1 on failure or when guid is null. ```APIDOC ## shareFullContent2Clipboard ### Description Builds the full runtime configuration via CoreConfigManager.getV2rayConfig and copies the pretty JSON to the clipboard. Returns 0 on success, -1 on failure or when guid is null. ### Method Kotlin function ### Signature ```kotlin fun shareFullContent2Clipboard(context: Context, guid: String?): Int ``` ### Parameters - **context** (Context) - Required - Android context for the clipboard - **guid** (String?) - Required - Server GUID; null returns -1 ### Returns - **Int** - `0` on success, `-1` on failure or when guid is null. ``` -------------------------------- ### initApp Source: https://github.com/2dust/v2rayng Initializes the settings manager at app start. It seeds default settings, routing rulesets, and performs legacy migrations. ```APIDOC ## initApp ### Description Initializes the settings manager at app start. It seeds default settings, routing rulesets, and performs legacy migrations. ### Method initApp ### Parameters #### Parameters - **context** (Context) - Required - The application context. ### Response No return value. ``` -------------------------------- ### decodeServerRaw(guid: String): String? Source: https://github.com/2dust/v2rayng Retrieves the raw configuration string for a server. Returns null if not found. ```APIDOC ## decodeServerRaw(guid: String): String? ### Description Retrieves the raw configuration string for a server. Returns null if not found. ### Method decodeServerRaw ### Parameters - **guid** (String) - Required - The server GUID. ### Response - **String?** - The raw configuration string, or null if not found. ``` -------------------------------- ### decodeAllServerList(): MutableList Source: https://github.com/2dust/v2rayng Retrieves all server GUIDs across all subscriptions. ```APIDOC ## decodeAllServerList(): MutableList ### Description Retrieves all server GUIDs across all subscriptions. ### Method decodeAllServerList ### Parameters None ### Response - **MutableList** - All server GUIDs. ``` -------------------------------- ### parse usage example Source: https://github.com/2dust/v2rayng Parses a masque:// URI with query parameters and shows resulting fields. ```kotlin val profile = MasqueFmt.parse( "masque://priv@example.com:443?publickey=pub&address=172.16.0.2%2F32&dns=1.1.1.1&alpn=h3#Masque" ) // profile.secretKey == "priv", profile.localAddress == "172.16.0.2/32", profile.alpn == "h3" ``` -------------------------------- ### getV2rayConfig Source: https://github.com/2dust/v2rayng Builds the V2Ray runtime configuration for a given server GUID. Returns a ConfigResult with status and JSON content on success, or an error message on failure. ```APIDOC ## getV2rayConfig ### Description Builds the V2Ray runtime configuration for a given server GUID. Returns a ConfigResult with status and JSON content on success, or an error message on failure. ### Method Function ### Signature ```kotlin fun getV2rayConfig(context: Context, guid: String): ConfigResult ``` ### Parameters - **context** (Context) - Required - App context (assets, package resolution) - **guid** (String) - Required - Selected server GUID ### Returns ConfigResult - `status=true` + pretty JSON `content` on success; `status=false` + `errorMessage` when the context cannot be built (`"Failed to build config context"`) or when any step throws (`"Failed to get V2ray config: "`). ### Request Example ```kotlin val result = CoreConfigManager.getV2rayConfig(context, guid) if (result.status) { Libv2ray.loadConfig(result.content) // hand to the native core } else { LogUtil.e(TAG, result.errorMessage) } ``` ``` -------------------------------- ### Usage example from CoreConfigManager.getV2rayConfig Source: https://github.com/2dust/v2rayng Shows how CoreConfigManager invokes CoreConfigContextBuilder.build. If the build returns null, it returns a failed ConfigResult; if the context is custom, it builds a custom config; otherwise it builds the unified config and converts to a result. ```kotlin // from CoreConfigManager.getV2rayConfig val configContext = CoreConfigContextBuilder.build(context, guid) ?: return ConfigResult(status = false, guid = guid, errorMessage = "Failed to build config context") if (configContext.isCustom) return buildV2rayCustomConfig(configContext) return toConfigResult(configContext, buildUnifiedConfig(configContext)) ``` -------------------------------- ### SocksFmt.parse error path example Source: https://github.com/2dust/v2rayng Shows that a missing port returns null, while a valid URI without credentials parses successfully. ```kotlin val profile = SocksFmt.parse("socks://host") // port <= 0 -> null val profile2 = SocksFmt.parse("socks://1.2.3.4:1234") // valid, no credentials ``` -------------------------------- ### Example — import failure handling Source: https://github.com/2dust/v2rayng Shows how parse returns null for invalid base64 or JSON, and how to handle it with a warning log. The profile is silently skipped by AngConfigManager. ```kotlin val profile = VmessFmt.parse("vmess://@@not-base64@@") if (profile == null) { // decode failed or JSON invalid: silently skipped by AngConfigManager LogUtil.w(TAG, "Invalid vmess link") } ``` -------------------------------- ### Example: pretty print with number normalization Source: https://github.com/2dust/v2rayng Shows how to pretty-print an outbound config after setting its port to 443; the custom Double serializer ensures the output is "port": 443, not 443.0. ```kotlin val outbound = CoreOutboundBuilder.convert(profile)!! outbound.settings?.let { it.port = 443 } val json = JsonUtil.toJsonPretty(outbound) // "port": 443 (not 443.0) ``` -------------------------------- ### LauncherManager object signature Source: https://github.com/2dust/v2rayng Public API of the LauncherManager singleton for starting, stopping, and restarting the core daemon from the UI. Import path: com.v2ray.ang.core.LauncherManager. ```kotlin object LauncherManager { fun startServiceFromToggle(context: Context): Boolean fun startService(context: Context, guid: String? = null) fun stopService(context: Context) fun restartService(context: Context) fun restartServiceOrStart(context: Context, startIfStopped: () -> Unit) } ``` -------------------------------- ### Example - importing a v2rayN export batch Source: https://github.com/2dust/v2rayng Shows how to call V2rayNFmt.parse with three v2rayn:// lines representing a policy group and two child profiles. The resulting policyGroupFilter is '^(Tokyo|Tokyo Alt)$'. ```kotlin val rawLines = listOf( "v2rayn://" + Utils.encode(jsonOf(shareItem(IndexId = "1", ConfigType = 101, childItems = "2,3"))), "v2rayn://" + Utils.encode(jsonOf(shareItem(IndexId = "2", ConfigType = 1, remarks = "Tokyo"))), "v2rayn://" + Utils.encode(jsonOf(shareItem(IndexId = "3", ConfigType = 1, remarks = "Tokyo Alt"))), ) val profiles = V2rayNFmt.parse(rawLines, subId = "sub-1") // profiles[0].policyGroupFilter == "^(Tokyo|Tokyo Alt)$" ``` -------------------------------- ### VlessFmt.parse example Source: https://github.com/2dust/v2rayng Parses a vless:// link with reality security and flow; maps fields like server, serverPort, password, flow, publicKey, shortId. ```kotlin val profile = VlessFmt.parse( "vless://uuid@example.com:443?encryption=none&security=reality&type=tcp&flow=xtls-rprx-vision&fp=chrome&pbk=pubkey&sid=abcd#Reality" ) // profile.server == "example.com", profile.serverPort == "443", profile.password == "uuid" // profile.flow == "xtls-rprx-vision", profile.publicKey == "pubkey", profile.shortId == "abcd" ``` -------------------------------- ### Subscription fetch with header callback Source: https://github.com/2dust/v2rayng Example of fetching a subscription URL with a custom User-Agent and parsing usage info from response headers. Catches IOException and logs failure. ```kotlin var usageInfo: SubscriptionUsageInfo? = null val body = try { HttpUtil.getUrlContentWithUserAgent( UrlContentRequest(url = subUrl, userAgent = "v2rayNG/1.0", timeout = 15000), onResponseHeaders = { headers -> usageInfo = SubscriptionInfoParser.parse( headers["Subscription-Userinfo"], headers["Profile-Title"], headers["Support-Url"], headers["Profile-Web-Page-Url"]) } ) } catch (e: IOException) { LogUtil.e(TAG, "subscription fetch failed: ${e.message}", e) "" } ``` -------------------------------- ### VlessFmt.toUri round trip example Source: https://github.com/2dust/v2rayng Decodes a config, builds the link with protocol scheme, and reparses to restore transport and security fields. ```kotlin val config = MmkvManager.decodeServerConfig(guid)!! val link = EConfigType.VLESS.protocolScheme + VlessFmt.toUri(config) val reparsed = VlessFmt.parse(link) // transport + security fields restored ``` -------------------------------- ### VlessFmt.parse error path example Source: https://github.com/2dust/v2rayng Returns null when the URI has no query string. ```kotlin val profile = VlessFmt.parse("vless://uuid@example.com") // no query -> null ``` -------------------------------- ### parse example with query parameters Source: https://github.com/2dust/v2rayng Parses a trojan:// URI with query parameters. The security parameter overrides the default 'tls', and allowInsecure=1 sets insecure to true. ```kotlin val profile = TrojanFmt.parse( "trojan://password@example.com:443?security=tls&sni=example.com&type=ws&path=%2Fws&allowInsecure=1#TrojanWS" ) // profile.security == "tls", profile.sni == "example.com", profile.network == "ws", // profile.insecure == true, profile.password == "password" ``` -------------------------------- ### Example - error handling (malformed lines are skipped) Source: https://github.com/2dust/v2rayng Shows that malformed lines are logged and skipped, so the batch continues and only valid lines are parsed. The result size is 1 when one line is invalid. ```kotlin val profiles = V2rayNFmt.parse(listOf("v2rayn://not-base64!", "v2rayn://" + goodJson), "sub-1") // profiles.size == 1 ``` -------------------------------- ### encodeServerRaw(guid: String, config: String) Source: https://github.com/2dust/v2rayng Stores the raw configuration string for a server. ```APIDOC ## encodeServerRaw(guid: String, config: String) ### Description Stores the raw configuration string for a server. ### Method encodeServerRaw ### Parameters - **guid** (String) - Required - The server GUID. - **config** (String) - Required - The raw configuration string. ### Response No return value. ``` -------------------------------- ### Usage from update path Source: https://github.com/2dust/v2rayng Example of parsing subscription headers inside AngConfigManager.updateConfigViaSub. The callback receives the HTTP headers and populates usageInfo. ```kotlin // inside AngConfigManager.updateConfigViaSub var usageInfo: SubscriptionUsageInfo? = null val text = HttpUtil.getUrlContentWithUserAgent(request) { headers -> usageInfo = SubscriptionInfoParser.parse( userInfo = headers["Subscription-Userinfo"], profileTitle = headers["Profile-Title"], supportUrl = headers["Support-Url"], webPageUrl = headers["Profile-Web-Page-Url"], ) } ``` -------------------------------- ### getV2rayConfig function signature Source: https://github.com/2dust/v2rayng Builds the V2Ray configuration for a selected server GUID. Returns a ConfigResult with status=true and pretty JSON content on success, or status=false with an error message when the context cannot be built or any step throws. ```kotlin fun getV2rayConfig(context: Context, guid: String): ConfigResult ``` -------------------------------- ### Example: safe deserialization pattern Source: https://github.com/2dust/v2rayng Uses fromJsonSafe to deserialize JSON into a ProfileItem, returning null on failure. ```kotlin val profile = JsonUtil.fromJsonSafe(json, ProfileItem::class.java) ?: return null ``` -------------------------------- ### Base64 decode/encode usage example Source: https://github.com/2dust/v2rayng Shows how to call Utils.decode and Utils.encode. decode returns the decoded JSON string; encode with removePadding=true produces URL-safe paddingless Base64. ```kotlin val plain = Utils.decode("eyJhZGQiOiIxLjIuMy40In0=") // -> {"add":"1.2.3.4"} val b64 = Utils.encode("method:password", removePadding = true) ``` -------------------------------- ### parse example without query string Source: https://github.com/2dust/v2rayng Parses a minimal trojan:// URI with no query string. In this branch, security defaults to 'tls', insecure is false, and network is 'tcp'. ```kotlin val profile = TrojanFmt.parse("trojan://password@example.com:443#Minimal") // profile.security == "tls", profile.insecure == false, profile.network == "tcp" ``` -------------------------------- ### parseWireguardConfFile example with config text Source: https://github.com/2dust/v2rayng Parses a WireGuard config string with [Interface] and [Peer] sections. The resulting profile fields are shown in the comment. ```kotlin val conf = """ [Interface] PrivateKey = abc Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = def Endpoint = vpn.example.com:51820 """.trimIndent() val profile = WireguardFmt.parseWireguardConfFile(conf) // profile.secretKey == "abc", profile.server == "vpn.example.com", profile.serverPort == "51820" ``` -------------------------------- ### Hysteria2Fmt.parse usage example Source: https://github.com/2dust/v2rayng Parses a sample hysteria2:// URI with obfs, obfs-password, and pinSHA256 parameters. ```kotlin val profile = Hysteria2Fmt.parse( "hysteria2://pw@example.com:443?obfs=salamander&obfs-password=secret&pinSHA256=abc#Hy2" ) // profile.obfs == "salamander", profile.obfsPassword == "secret", profile.pinnedCA256 == "abc" ``` -------------------------------- ### measureOutboundDelay usage example Source: https://github.com/2dust/v2rayng Gets a speedtest config, measures delay, and stores the result if non-negative. ```kotlin val result = CoreConfigManager.getV2rayConfig4Speedtest(context, guid) if (result.status) { val delay = CoreNativeManager.measureOutboundDelay(result.content, AppConfig.DELAY_TEST_URL) if (delay >= 0) MmkvManager.encodeServerTestDelayMillis(guid, delay) } ``` -------------------------------- ### build method signature Source: https://github.com/2dust/v2rayng Signature of the build method. It accepts an app context and a selected server GUID, returning a CoreConfigContext or null when the profile cannot be loaded or primary outbound resolution fails. ```kotlin fun build(context: Context, guid: String): CoreConfigContext? ``` -------------------------------- ### removeServer(guid: String) Source: https://github.com/2dust/v2rayng Removes a server profile by its GUID. ```APIDOC ## removeServer(guid: String) ### Description Removes a server profile by its GUID. ### Method removeServer ### Parameters - **guid** (String) - Required - The server GUID to remove. ### Response No return value. ``` -------------------------------- ### setSelectServer(guid: String) Source: https://github.com/2dust/v2rayng Sets the currently selected server by its GUID. ```APIDOC ## setSelectServer(guid: String) ### Description Sets the currently selected server by its GUID. ### Method setSelectServer ### Parameters - **guid** (String) - Required - The GUID of the server to select. ### Response No return value. ``` -------------------------------- ### removeServers(guids: List, subscriptionId: String) Source: https://github.com/2dust/v2rayng Removes multiple servers by their GUIDs, optionally scoped to a subscription. ```APIDOC ## removeServers(guids: List, subscriptionId: String) ### Description Removes multiple servers by their GUIDs, optionally scoped to a subscription. ### Method removeServers ### Parameters - **guids** (List) - Required - The list of server GUIDs to remove. - **subscriptionId** (String) - Required - The subscription ID to scope the removal. ### Response No return value. ``` -------------------------------- ### decodeStartOnBoot(): Boolean Source: https://github.com/2dust/v2rayng Retrieves the start-on-boot setting. ```APIDOC ## decodeStartOnBoot(): Boolean ### Description Retrieves the start-on-boot setting. ### Method decodeStartOnBoot ### Parameters None ### Response - **Boolean** - The start-on-boot flag. ``` -------------------------------- ### encodeServerConfig / decodeServerConfig Source: https://github.com/2dust/v2rayng Encodes and decodes server configuration (ProfileItem) by GUID. Encoding generates a new UUID if GUID is blank and persists the payload. ```APIDOC ## encodeServerConfig / decodeServerConfig ### Description `encodeServerConfig` persists a `ProfileItem` under the given GUID (or a new UUID if blank) and updates subscription lists. `decodeServerConfig` retrieves the stored `ProfileItem` for a GUID. ### Method encodeServerConfig / decodeServerConfig ### Parameters - **guid** (String) - Required - Server GUID; when blank a new UUID is generated and returned. - **config** (ProfileItem) - Required - Profile serialized to JSON. ### Response - **encodeServerConfig** returns the effective GUID (String). May throw `ProfileStorageException`. - **decodeServerConfig** returns the `ProfileItem?` or null if not found. ### Request Example ```kotlin val guid = MmkvManager.encodeServerConfig("", VmessFmt.parse(link)!!) val reloaded: ProfileItem? = MmkvManager.decodeServerConfig(guid) ``` ``` -------------------------------- ### encodeStartOnBoot(startOnBoot: Boolean) Source: https://github.com/2dust/v2rayng Stores the start-on-boot setting. ```APIDOC ## encodeStartOnBoot(startOnBoot: Boolean) ### Description Stores the start-on-boot setting. ### Method encodeStartOnBoot ### Parameters - **startOnBoot** (Boolean) - Required - The start-on-boot flag. ### Response No return value. ``` -------------------------------- ### init method signature Source: https://github.com/2dust/v2rayng Initializes the WebDAV client with the given config. Builds OkHttp client with all timeouts set to config.timeoutSeconds. Overwrites previous config. ```kotlin fun init(config: WebDavConfig) ``` -------------------------------- ### encodeServerConfig and decodeServerConfig signatures Source: https://github.com/2dust/v2rayng encodeServerConfig persists a ProfileItem as JSON under the given GUID, generating a new UUID if blank, and prepends the key to the subscription's server list. decodeServerConfig retrieves the ProfileItem for a GUID. May throw ProfileStorageException. ```kotlin fun encodeServerConfig(guid: String, config: ProfileItem): String fun decodeServerConfig(guid: String): ProfileItem? ``` -------------------------------- ### encodeSubscription(guid: String, subItem: SubscriptionItem) Source: https://github.com/2dust/v2rayng Stores a subscription item. ```APIDOC ## encodeSubscription(guid: String, subItem: SubscriptionItem) ### Description Stores a subscription item. ### Method encodeSubscription ### Parameters - **guid** (String) - Required - The subscription GUID. - **subItem** (SubscriptionItem) - Required - The subscription item to store. ### Response No return value. ``` -------------------------------- ### init(config: WebDavConfig) Source: https://github.com/2dust/v2rayng Initializes the WebDAV client with the provided configuration. Must be called before any transfer operations. ```APIDOC ## init(config: WebDavConfig) ### Description Initializes the WebDAV client with the provided configuration. Must be called before any transfer operations. ### Method init ### Parameters #### Parameters - **config** (WebDavConfig) - Required - Server + credentials + path + timeout ### Response No return value. ``` -------------------------------- ### encodeServerTestDelayMillis(guid: String, testResult: Long) Source: https://github.com/2dust/v2rayng Stores the test delay (in milliseconds) for a server. ```APIDOC ## encodeServerTestDelayMillis(guid: String, testResult: Long) ### Description Stores the test delay (in milliseconds) for a server. ### Method encodeServerTestDelayMillis ### Parameters - **guid** (String) - Required - The server GUID. - **testResult** (Long) - Required - The test delay in milliseconds. ### Response No return value. ``` -------------------------------- ### decodeServerList(subscriptionId: String): MutableList Source: https://github.com/2dust/v2rayng Retrieves the list of server GUIDs for a given subscription. ```APIDOC ## decodeServerList(subscriptionId: String): MutableList ### Description Retrieves the list of server GUIDs for a given subscription. ### Method decodeServerList ### Parameters - **subscriptionId** (String) - Required - The subscription identifier. ### Response - **MutableList** - The list of server GUIDs. ``` -------------------------------- ### removeInvalidServer(guid: String): Int Source: https://github.com/2dust/v2rayng Removes a server if it is invalid. Returns 1 if removed, 0 otherwise. ```APIDOC ## removeInvalidServer(guid: String): Int ### Description Removes a server if it is invalid. Returns 1 if removed, 0 otherwise. ### Method removeInvalidServer ### Parameters - **guid** (String) - Required - The server GUID to check and remove. ### Response - **Int** - 1 if the server was removed, 0 otherwise. ``` -------------------------------- ### initCoreEnv method signature Source: https://github.com/2dust/v2rayng Initializes the core environment with the user-asset directory and device ID. Guarded by an AtomicBoolean; concurrent calls are no-ops. On exception, the flag resets and the exception is re-thrown. ```kotlin fun initCoreEnv(context: Context?) ``` -------------------------------- ### Example — parse error path Source: https://github.com/2dust/v2rayng Shows that parseVmessStd returns null when the URI has no query string. ```kotlin val profile = VmessFmt.parseVmessStd("vmess://uuid@example.com:443") // no query -> null ``` -------------------------------- ### initialize Source: https://github.com/2dust/v2rayng Initializes the MMKV native library with a recovery handler. Called once from AngApplication. ```APIDOC ## initialize ### Description Initializes the MMKV native library with a recovery handler that returns `MMKVRecoverStrategic.OnErrorRecover` on CRC or file-length failure. Called once from `AngApplication`. Log level is `Debug` in debug builds, `Info` otherwise. ### Method initialize ### Parameters - **context** (Context) - Required - The application context. ### Response No return value. ``` -------------------------------- ### decodeServerAffiliationInfo(guid: String): ServerAffiliationInfo? Source: https://github.com/2dust/v2rayng Decodes affiliation information (e.g., subscription ID) for a server. Returns null if not found. ```APIDOC ## decodeServerAffiliationInfo(guid: String): ServerAffiliationInfo? ### Description Decodes affiliation information (e.g., subscription ID) for a server. Returns null if not found. ### Method decodeServerAffiliationInfo ### Parameters - **guid** (String) - Required - The server GUID. ### Response - **ServerAffiliationInfo?** - The affiliation info, or null if not found. ``` -------------------------------- ### initCoreEnv Source: https://github.com/2dust/v2rayng Initializes the core environment with the user-asset directory and device ID. Guarded by an AtomicBoolean; concurrent and repeated calls are no-ops. ```APIDOC ## initCoreEnv ### Description Initializes the core environment with the user-asset directory and device ID. Guarded by an AtomicBoolean; concurrent and repeated calls are no-ops. ### Method initCoreEnv ### Signature ```kotlin fun initCoreEnv(context: Context?) ``` ### Parameters - **context** (Context?) - Required - Application context; applicationContext is registered with Seq.setContext ### Response No return value. ### Request Example ```kotlin try { CoreNativeManager.initCoreEnv(context) } catch (e: Exception) { LogUtil.e(TAG, "Core init failed, will retry on next start", e) } ``` ``` -------------------------------- ### Service class selection in startContextService Source: https://github.com/2dust/v2rayng Chooses the service class based on root mode, VPN mode, or proxy-only. Root mode requires RootManager.isRootAvailable() else toast_root_required. ```kotlin val intent = if (isRootMode) Intent(context.applicationContext, CoreRootService::class.java) else if (isVpnMode()) Intent(context.applicationContext, CoreVpnService::class.java) else Intent(context.applicationContext, CoreProxyOnlyService::class.java) ``` -------------------------------- ### encodeServerList(serverList: MutableList, subscriptionId: String) Source: https://github.com/2dust/v2rayng Stores the list of server GUIDs for a given subscription. Used to maintain the group index. ```APIDOC ## encodeServerList(serverList: MutableList, subscriptionId: String) ### Description Stores the list of server GUIDs for a given subscription. Used to maintain the group index. ### Method encodeServerList ### Parameters - **serverList** (MutableList) - Required - The list of server GUIDs. - **subscriptionId** (String) - Required - The subscription identifier. ### Response No return value. ``` -------------------------------- ### getV2rayConfig4Speedtest Source: https://github.com/2dust/v2rayng Builds the V2Ray runtime configuration for speed testing. Same pipeline as getV2rayConfig, then strips inbounds, routing rules, DNS, fakedns, stats, policy, and outbound mux blocks. ```APIDOC ## getV2rayConfig4Speedtest ### Description Builds the V2Ray runtime configuration for speed testing. Same pipeline as getV2rayConfig, then strips inbounds, routing rules, DNS, fakedns, stats, policy, and outbound mux blocks. ### Method Function ### Signature ```kotlin fun getV2rayConfig4Speedtest(context: Context, guid: String): ConfigResult ``` ### Parameters - **context** (Context) - Required - App context (assets, package resolution) - **guid** (String) - Required - Selected server GUID ### Returns ConfigResult - Same as getV2rayConfig, but with speedtest-specific post-processing. ### Request Example ```kotlin val result = CoreConfigManager.getV2rayConfig4Speedtest(context, guid) val delay = CoreNativeManager.measureOutboundDelay(result.content, AppConfig.DELAY_TEST_URL) ``` ``` -------------------------------- ### userAssetPath Source: https://github.com/2dust/v2rayng Returns the path to the user asset directory. ```APIDOC ## userAssetPath ### Description Returns the path to the user asset directory. ### Method Function ### Signature `fun userAssetPath(context: Context?): String` ### Parameters - **context** (Context?) - Required - The application context. ### Returns - **String** - The path to the user asset directory. ``` -------------------------------- ### initApp(context: Context) Source: https://github.com/2dust/v2rayng Initializes the SettingsManager with the application context. This must be called before using any other methods. ```APIDOC ## initApp(context: Context) ### Description Initializes the SettingsManager with the application context. This must be called before using any other methods. ### Method initApp ### Parameters - **context** (Context) - Required - The application context. ### Response No return value. ``` -------------------------------- ### Catching ProfileStorageException in consumer code Source: https://github.com/2dust/v2rayng Example of catching ProfileStorageException when calling AngConfigManager.importBatchConfig. Since the class is internal, external consumers should catch IllegalStateException instead. ```kotlin try { AngConfigManager.importBatchConfig(server, subid, append) } catch (e: ProfileStorageException) { // internal: only visible inside module, or catch IllegalStateException LogUtil.e(TAG, "storage write failed: ${e.message}", e) } ``` -------------------------------- ### initialize(context: Context) Source: https://github.com/2dust/v2rayng Initializes the MMKV storage manager with the given Android context. Must be called before any other operations. ```APIDOC ## initialize(context: Context) ### Description Initializes the MMKV storage manager with the given Android context. Must be called before any other operations. ### Method initialize ### Parameters - **context** (Context) - Required - The Android application context. ### Response No return value. ``` -------------------------------- ### WebDavManager object signature Source: https://github.com/2dust/v2rayng Public surface of the WebDavManager singleton: init, uploadFile, and downloadFile methods. Must call init before any transfer. ```kotlin object WebDavManager { fun init(config: WebDavConfig) suspend fun uploadFile(localFile: File, remoteFileName: String): Boolean suspend fun downloadFile(remoteFileName: String, destFile: File): Boolean } ``` -------------------------------- ### readLegacyServerList(): String? Source: https://github.com/2dust/v2rayng Reads the legacy server list from storage. Returns the raw string or null if not present. ```APIDOC ## readLegacyServerList(): String? ### Description Reads the legacy server list from storage. Returns the raw string or null if not present. ### Method readLegacyServerList ### Parameters None ### Response - **String?** - The legacy server list as a string, or null if not found. ``` -------------------------------- ### openUri(context, uriString) Source: https://github.com/2dust/v2rayng Opens a URI using an ACTION_VIEW intent. ```APIDOC ## openUri(context, uriString) ### Description Opens a URI using an ACTION_VIEW intent. ### Method Function ### Parameters - **context** (Context) - Required - The application context. - **uriString** (String) - Required - The URI string to open. ``` -------------------------------- ### decodeSettingsString(key: String): String? Source: https://github.com/2dust/v2rayng Retrieves a string setting value. Returns null if not found. ```APIDOC ## decodeSettingsString(key: String): String? ### Description Retrieves a string setting value. Returns null if not found. ### Method decodeSettingsString ### Parameters - **key** (String) - Required - The setting key. ### Response - **String?** - The setting value, or null if not found. ```