### Start HTTP Server Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Starts the HTTP server for the configuration API. Specify the listen address and port. Returns an error message if startup fails. ```kotlin fun startHttp(listenAt: String): String? ``` ```kotlin val error = Clash.startHttp("127.0.0.1:9090") if (error != null) { println("Failed to start HTTP server: $error") } ``` -------------------------------- ### Start Clash.Meta Service Source: https://github.com/metacubex/clashmetaforandroid/blob/main/README.md Send an intent to `ExternalControlActivity` with the action `com.github.metacubex.clash.meta.action.START_CLASH` to start the service. ```java Send intent to activity com.github.kr328.clash.ExternalControlActivity with action com.github.metacubex.clash.meta.action.START_CLASH ``` -------------------------------- ### START_CLASH Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Starts the Clash service if it is not already running. If the service is already running, a toast message indicating this will be shown. On failure to start, a "unable to start VPN" toast is displayed. No special permissions are required. ```APIDOC ## START_CLASH ### Description Starts the Clash service if not already running. ### Intent Action `com.github.metacubex.clash.meta.action.START_CLASH` ### Behavior - If Clash is not running: Starts the service - If Clash is already running: Shows toast "already started" - On start failure: Shows toast "unable to start VPN" ### Example (Kotlin) ```kotlin val intent = Intent("com.github.metacubex.clash.meta.action.START_CLASH") intent.setPackage("com.github.metacubex.clash.meta") startActivity(intent) ``` ### Example (Bash) ```bash adb shell am start -n com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity -a com.github.metacubex.clash.meta.action.START_CLASH ``` ``` -------------------------------- ### Handle TUN Start Failure Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/errors.md Example of catching ClashExceptions when starting the TUN interface, which can be caused by invalid file descriptors, unsupported stacks, or permission issues. ```kotlin try { Clash.startTun( fd = tunFd, stack = "gvisor", gateway = gateway, portal = portal, dns = dnsServer, markSocket = { fd -> true }, querySocketUid = { proto, src, dst -> 0 } ) } catch (e: ClashException) { Log.e("Clash", "TUN start failed: ${e.message}") // Show VPN permission dialog } ``` -------------------------------- ### startHttp Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Starts the HTTP server, which is used for the configuration API. It listens on a specified address and port. ```APIDOC ## Function: startHttp ### Description Starts the HTTP server for configuration API. It listens on a specified address and port. ### Parameters - **listenAt** (String) - Required - Listen address in format "address:port" (e.g., "127.0.0.1:9090") ### Returns `String?` — Error message if start fails; null if successful ### Throws None ### Example ```kotlin val error = Clash.startHttp("127.0.0.1:9090") if (error != null) { println("Failed to start HTTP server: $error") } ``` ``` -------------------------------- ### Implement IFetchObserver Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/remote-service-api.md Example implementation of the IFetchObserver interface to handle fetch status updates and print progress information. ```kotlin val observer = IFetchObserver { status -> println("${status.action}: ${status.progress}/${status.max}") when (status.action) { FetchStatus.Action.FetchConfiguration -> println("Fetching...") FetchStatus.Action.Verifying -> println("Verifying...") else -> {} } } profileManager.commit(profileId, observer) ``` -------------------------------- ### Implement ILogObserver Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/remote-service-api.md Example implementation of the ILogObserver interface to process incoming log messages. ```kotlin class MyLogObserver : ILogObserver.Stub() { override fun newItem(log: LogMessage) { println("[${log.level}] ${log.message}") } } ``` -------------------------------- ### nativeStartHttp Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Starts the HTTP API server, allowing external control and monitoring of the Clash core. ```APIDOC ## nativeStartHttp ### Description Starts HTTP API server. ### Method external fun ### Parameters #### Path Parameters - **listenAt** (String) - Required - Listen address (e.g., "127.0.0.1:9090") ### Returns String? - Error message or null on success ### Delegates to: HTTP server startup ``` -------------------------------- ### Configure Android SDK Path Source: https://github.com/metacubex/clashmetaforandroid/blob/main/README.md Create a `local.properties` file in the project root and specify the path to your Android SDK installation. ```properties sdk.dir=/path/to/android-sdk ``` -------------------------------- ### Start TUN Interface Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Starts the TUN interface for system-wide traffic interception. Requires file descriptor, network stack type, gateway, portal, DNS, and callback functions for socket marking and UID querying. ```kotlin fun startTun( fd: Int, stack: String, gateway: String, portal: String, dns: String, markSocket: (Int) -> Boolean, querySocketUid: (protocol: Int, source: InetSocketAddress, target: InetSocketAddress) -> Int ) ``` ```kotlin Clash.startTun( fd = tunFd, stack = "gvisor", gateway = "192.168.0.1", portal = "192.168.0.2", dns = "127.0.0.1:8853", markSocket = { fd -> // Mark socket for exclusion true }, querySocketUid = { protocol, source, target -> // Return UID for the socket 1000 } ) ``` -------------------------------- ### Kotlin Example: Import Profile with URL and Interval Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Demonstrates how to construct and launch an intent to import a profile from a URL, specifying a name and update interval. Ensure the URL is properly encoded. ```kotlin val profileUrl = "https://example.com/profile.yaml" val encodedUrl = URLEncoder.encode(profileUrl, "UTF-8") val uri = "clash://install-config?url=$encodedUrl&name=My%20Profile&type=url&update-interval=60" val intent = Intent(Intent.ACTION_VIEW, uri.toUri()) startActivity(intent) ``` -------------------------------- ### Start Clash Service Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Initiate the Clash service using this intent. If the service is already running, a toast message will indicate this. Failure to start will also be indicated by a toast. ```kotlin val intent = Intent("com.github.metacubex.clash.meta.action.START_CLASH") intent.setPackage("com.github.metacubex.clash.meta") startActivity(intent) ``` ```bash adb shell am start -n com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity \ -a com.github.metacubex.clash.meta.action.START_CLASH ``` -------------------------------- ### Bash Script: Start Clash Service Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md This script uses ADB to start the Clash service by sending a specific intent to the ExternalControlActivity. Ensure the package name and activity are correct. ```bash #!/bin/bash # Start Clash service adb shell am start -n com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity \ -a com.github.metacubex.clash.meta.action.START_CLASH ``` -------------------------------- ### nativeStartTun Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Starts the TUN interface, enabling network traffic interception and routing. ```APIDOC ## nativeStartTun ### Description Starts TUN interface with callbacks. ### Method external fun ### Parameters #### Path Parameters - **fd** (Int) - Required - TUN device file descriptor - **stack** (String) - Required - Network stack ("gvisor" or "system") - **gateway** (String) - Required - Gateway IP - **portal** (String) - Required - Portal IP - **dns** (String) - Required - DNS server address - **cb** (TunInterface) - Required - Callback interface for socket operations ### Returns None ### Delegates to: TUN device initialization ``` -------------------------------- ### startTun Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Starts the TUN interface for system-wide traffic interception. This function requires a file descriptor for the TUN device and network configuration details. ```APIDOC ## Function: startTun ### Description Starts the TUN interface for system-wide traffic interception. This function requires a file descriptor for the TUN device and network configuration details. ### Parameters - **fd** (Int) - Required - File descriptor for TUN device - **stack** (String) - Required - Network stack type ("gvisor" or "system") - **gateway** (String) - Required - Gateway IP address (e.g., "192.168.0.1") - **portal** (String) - Required - Portal IP address - **dns** (String) - Required - DNS server address - **markSocket** ((Int) -> Boolean) - Required - Callback to mark sockets for exclusion - **querySocketUid** ((Int, InetSocketAddress, InetSocketAddress) -> Int) - Required - Callback to query socket UID ### Returns `Unit` ### Throws `ClashException` if TUN startup fails ### Example ```kotlin Clash.startTun( fd = tunFd, stack = "gvisor", gateway = "192.168.0.1", portal = "192.168.0.2", dns = "127.0.0.1:8853", markSocket = { fd -> // Mark socket for exclusion true }, querySocketUid = { protocol, source, target -> // Return UID for the socket 1000 } ) ``` ``` -------------------------------- ### Bash Example: Import Profile via ADB Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Use ADB to send an intent for profile import. This is useful for scripting and automation, allowing remote control of the application. ```bash URL="https://example.com/profile.yaml" ENCODED_URL=$(python3 -c "import urllib.parse; print(urllib.parse.quote('''$URL'''))") adb shell am start -a android.intent.action.VIEW \ -d "clash://install-config?url=$ENCODED_URL&name=MyProfile&type=url&update-interval=60" \ -n com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity ``` -------------------------------- ### Example Encoded URL for Profile Import Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md This is an example of a fully encoded URL string used for importing a profile via the clash:// scheme, including the profile URL, name, type, and update interval. ```text clash://install-config?url=https%3A%2F%2Fexample.com%2Fprofile.yaml&name=MyProfile&type=url&update-interval=60 ``` -------------------------------- ### Start Clash Service Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Starts the Clash service using a specific intent action. This is useful for automation scripts or other applications that need to ensure the Clash service is running. ```APIDOC ## Start Clash Service ### Description Starts the Clash service. This action is intended for automation scripts or other applications that need to programmatically start the Clash service. ### Method `com.github.metacubex.clash.meta.action.START_CLASH` ### Endpoint `com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity` ### Parameters None ### Request Example (Bash) ```bash #!/bin/bash # Start Clash service adb shell am start -n com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity \ -a com.github.metacubex.clash.meta.action.START_CLASH ``` ### Behavior - If the service is already running, a toast message "external_control_started" is shown. - If there is no profile configured, a toast message is shown, and the service does not start. - If the VPN fails to start, a toast message "unable_to_start_vpn" is shown. ``` -------------------------------- ### Bridge Initialization Using Global Context Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/global-context.md Illustrates how the Bridge object accesses the application context via Global.application during its initialization to get file paths and package information. ```kotlin object Bridge { init { System.loadLibrary("bridge") val ctx = Global.application // Access via Global val home = ctx.filesDir.resolve("clash").absolutePath val versionName = ctx.packageManager.getPackageInfo(ctx.packageName, 0).versionName ?: "unknown" val sdkVersion = Build.VERSION.SDK_INT nativeInit(home, versionName, sdkVersion) } } ``` -------------------------------- ### Handle ClashException in Try-Catch Block Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/types.md Example demonstrating how to catch and handle ClashException during Clash core operations like loading a configuration. ```kotlin try { Clash.load(file).await() } catch (e: ClashException) { println("Clash error: ${e.message}") } ``` -------------------------------- ### QR Code Content for Profile Import Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md A profile can be imported by scanning a QR code containing a clash://install-config URL. This example shows the structure of such a URL for a remote profile. ```text clash://install-config?url=https%3A%2F%2Fexample.com%2Fprofile.yaml&name=RemoteProfile&type=url&update-interval=120 ``` -------------------------------- ### Start Clash Service via ADB Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/README.md Initiate the Clash service on an Android device using ADB. This command is useful for automated testing or remote control. ```bash adb shell am start -n com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity \ -a com.github.metacubex.clash.meta.action.START_CLASH ``` -------------------------------- ### nativeNotifyInstalledAppChanged Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Notifies the Clash core about changes in installed applications (installations or uninstallations). ```APIDOC ## nativeNotifyInstalledAppChanged ### Description Notifies of app installation/uninstallation changes. ### Method external fun ### Parameters #### Path Parameters - **uidList** (String) - Required - Comma-separated "uid:package" strings (e.g., "1000:com.android.system,10001:com.example") ### Returns None ### Delegates to: App list update handler ``` -------------------------------- ### Query Current Configuration Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-manager-api.md Obtain the current Clash configuration settings. This is useful for initializing the UI or understanding the active setup. ```kotlin val config = clashManager.queryConfiguration() // Use for UI initialization ``` -------------------------------- ### Notify Installed Apps Changes Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Informs the Clash engine about changes in installed applications, crucial for app-based routing rules. Provide a list of (UID, package name) pairs. ```kotlin val apps = listOf( 1000 to "com.android.system", 10001 to "com.example.app" ) Clash.notifyInstalledAppsChanged(apps) ``` -------------------------------- ### Access System Cache Directory Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/configuration.md Get the path to the system's cache directory. This is used for temporary files and downloads. ```kotlin val cacheDir = context.cacheDir ``` -------------------------------- ### Handle Fetch and Validation Failure Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/errors.md Example for handling ClashExceptions during the fetch and validation process, covering network errors, invalid configurations, parse errors, and decryption failures. ```kotlin try { Clash.fetchAndValid( path = configFile, url = sourceUrl, force = true, reportStatus = { status -> println("${status.action}: ${status.progress}/${status.max}") } ).await() } catch (e: ClashException) { Log.e("Clash", "Fetch failed: ${e.message}") // Show error dialog to user // Suggest checking source URL or network connection } ``` -------------------------------- ### Import Profile via External Intent Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/README.md Install a Clash profile using an external intent with a specified URL and name. This method is suitable for launching profile imports from other applications. ```bash adb shell am start -a android.intent.action.VIEW \ -d 'clash://install-config?url=https%3A%2F%2Fexample.com%2Fprofile.yaml&name=MyProfile' ``` -------------------------------- ### Access Clash Home Directory Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/configuration.md Get the path to the Clash home directory. This directory stores configuration files, provider cache, override storage, and geolocation databases. ```kotlin val clashHome = context.filesDir.resolve("clash") ``` -------------------------------- ### Native Function Declaration: nativeStartHttp Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Declares the external native function to start the HTTP API server. It takes a listen address and returns an error message or null on success. ```kotlin external fun nativeStartHttp(listenAt: String): String? ``` -------------------------------- ### Native Function Declaration: nativeStartTun Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Declares the external native function to start the TUN interface. It requires a file descriptor, network stack configuration, gateway, portal, DNS, and a callback interface. ```kotlin external fun nativeStartTun( fd: Int, stack: String, gateway: String, portal: String, dns: String, cb: TunInterface ) ``` -------------------------------- ### Import and Activate a Profile Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/README.md Create a new profile from a URL, monitor its fetch progress, and then activate it. Ensure the profile URL is valid. ```kotlin val profileId = profileManager.create( type = Profile.Type.Url, name = "My Profile", source = "https://example.com/config.yaml" ) profileManager.commit(profileId, observer = object : IFetchObserver { override fun updateStatus(status: FetchStatus) { println("${status.action}: ${status.progress}/${status.max}") } }) val profile = profileManager.queryByUUID(profileId) if (profile != null) { profileManager.setActive(profile) } ``` -------------------------------- ### Configure Signing Properties Source: https://github.com/metacubex/clashmetaforandroid/blob/main/README.md Create a `signing.properties` file with your keystore details for signing the application. ```properties keystore.path=/path/to/keystore/file keystore.password= key.alias= key.password= ``` -------------------------------- ### Toggle Clash Service State Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Use this intent to toggle the Clash service. It starts the service if stopped, and stops it if running. Ensure a profile is selected before starting. ```kotlin val intent = Intent("com.github.metacubex.clash.meta.action.TOGGLE_CLASH") intent.setPackage("com.github.metacubex.clash.meta") startActivity(intent) ``` ```bash adb shell am start -n com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity \ -a com.github.metacubex.clash.meta.action.TOGGLE_CLASH ``` -------------------------------- ### Signing Properties for Release Builds Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/configuration.md Configure signing details for release builds by providing the path to the keystore file, its password, and the key alias and password. ```properties keystore.path=/path/to/release.keystore keystore.password=keystorepass key.alias=release_key key.password=keypass ``` -------------------------------- ### nativeQueryTrafficTotal Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Queries the total cumulative traffic transferred since the start. ```APIDOC ## nativeQueryTrafficTotal ### Description Queries total cumulative traffic. ### Method external fun ### Parameters None ### Returns Long - Total bytes transferred ### Delegates to: None ``` -------------------------------- ### Build Release Version Source: https://github.com/metacubex/clashmetaforandroid/blob/main/README.md Execute this Gradle command to build the application's alpha release version. ```bash ./gradlew app:assembleAlphaRelease ``` -------------------------------- ### Application Initialization and Termination Pattern Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/global-context.md A common pattern for initializing and cleaning up the Global context within a custom Application class. ```kotlin class MainApplication : Application() { override fun onCreate() { super.onCreate() Global.init(this) // Make context available setupCrashHandler() } override fun onTerminate() { Global.destroy() // Clean up super.onTerminate() } } ``` -------------------------------- ### Accessing SharedPreferences Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/global-context.md Gets SharedPreferences for configuration and retrieves an integer value. ```kotlin val prefs = Global.application.getSharedPreferences("config", Context.MODE_PRIVATE) val value = prefs.getInt("key", 0) ``` -------------------------------- ### Import Profile via URL Scheme Source: https://github.com/metacubex/clashmetaforandroid/blob/main/README.md Import a profile using the `clash://install-config` or `clashmeta://install-config` URL schemes, followed by the encoded profile URL. ```url clash://install-config?url= ``` ```url clashmeta://install-config?url= ``` -------------------------------- ### Configuration Reference Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/README.md Details build, runtime, and environment configuration, including Gradle properties, local configuration files, manifest configuration, and TUN configuration. ```APIDOC ## Configuration Reference Build, runtime, and environment configuration: - **Build Configuration** - Gradle properties and build variants - **Local Configuration Files** - local.properties, signing.properties - **Manifest Configuration** - Declared components, permissions, intent filters - **Runtime Configuration** - Configuration overrides structure and fields - **Profile Configuration** - Profile types and database schema - **TUN Configuration** - Network stack options and parameters - **Environmental Paths** - Directory structure and access patterns - **Version Management** - Release versioning ``` -------------------------------- ### Fetch and Validate Configuration Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Fetches a configuration from a URL, validates it, and saves it to a local path asynchronously. Supports forcing a refetch and ignoring cache. ```kotlin external fun nativeFetchAndValid( completable: FetchCallback, path: String, url: String, force: Boolean ) ``` -------------------------------- ### Handle Configuration Load Failure Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/errors.md Demonstrates catching a ClashException during configuration loading, which can occur due to invalid YAML, file not found, or permission issues. ```kotlin try { Clash.load(configFile).await() } catch (e: ClashException) { Log.e("Clash", "Load failed: ${e.message}") // Load previous config as fallback } ``` -------------------------------- ### TOGGLE_CLASH Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Toggles the Clash service state. Starts the service if it is stopped, and stops it if it is running. Requires no special permissions as it operates within the same package. ```APIDOC ## TOGGLE_CLASH ### Description Toggles the Clash service state (starts if stopped, stops if running). ### Intent Action `com.github.metacubex.clash.meta.action.TOGGLE_CLASH` ### Behavior - If Clash is running: Stops the service - If Clash is stopped: Starts the service (displays error if no profile selected) ### Example (Kotlin) ```kotlin val intent = Intent("com.github.metacubex.clash.meta.action.TOGGLE_CLASH") intent.setPackage("com.github.metacubex.clash.meta") startActivity(intent) ``` ### Example (Bash) ```bash adb shell am start -n com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity -a com.github.metacubex.clash.meta.action.TOGGLE_CLASH ``` ``` -------------------------------- ### Load Configuration from File Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Loads a Clash configuration from a local YAML file. Use this after fetching or modifying a configuration file. Errors during loading are reported via exception completion. ```kotlin fun load(path: File): CompletableDeferred ``` ```kotlin launch { try { Clash.load(File(configPath)).await() println("Configuration loaded") } catch (e: ClashException) { println("Failed to load config: ${e.message}") } } ``` -------------------------------- ### Query Proxy Group Names Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Queries proxy group names as a JSON array. Use this to get a list of available proxy groups. ```kotlin external fun nativeQueryGroupNames(excludeNotSelectable: Boolean): String ``` -------------------------------- ### nativeQueryConfiguration Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Queries the current configuration of the system and returns it as a JSON string. This is useful for understanding the current state of the application's settings. ```APIDOC ## Function: nativeQueryConfiguration Queries current configuration as JSON. ### Returns `String` — JSON serialized UiConfiguration ``` -------------------------------- ### Accessing Application Context from Anywhere Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/global-context.md Demonstrates how to access the application context using Global.application from any class, without needing to pass a Context parameter. ```kotlin // In any class (no Activity/Context parameter needed) val app = Global.application val prefs = app.getSharedPreferences("config", Context.MODE_PRIVATE) val dir = app.filesDir ``` -------------------------------- ### Query Total Traffic Statistics Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-manager-api.md Get the cumulative data transferred through the Clash tunnel. The result is in bytes and can be converted to MB or GB for easier reading. ```kotlin val totalBytes = clashManager.queryTrafficTotal() println("Total traffic: ${totalBytes / 1024 / 1024} MB") ``` -------------------------------- ### Kotlin Function: Toggle Clash Service Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md This function sends an intent to toggle the Clash service. It sets the action and package name for the intent, then starts the activity. ```kotlin fun toggleClash(context: Context) { val intent = Intent("com.github.metacubex.clash.meta.action.TOGGLE_CLASH") intent.setPackage("com.github.metacubex.clash.meta") context.startActivity(intent) } ``` -------------------------------- ### Fetch and Validate Configuration Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Fetches a configuration from a URL, validates it, and saves it to a specified file. Use this to dynamically update Clash configurations. It supports progress reporting and can be forced to ignore cache. ```kotlin fun fetchAndValid( path: File, url: String, force: Boolean, reportStatus: (FetchStatus) -> Unit ): CompletableDeferred ``` ```kotlin launch { try { Clash.fetchAndValid( path = File(context.cacheDir, "profile.yaml"), url = "https://example.com/profile", force = true, reportStatus = { status -> println("Fetch progress: ${status.progress}/${status.max}") when (status.action) { FetchStatus.Action.FetchConfiguration -> println("Fetching config...") FetchStatus.Action.Verifying -> println("Verifying...") else -> {} } } ).await() println("Fetch completed successfully") } catch (e: ClashException) { println("Fetch failed: ${e.message}") } } ``` -------------------------------- ### Handle Tunnel State Query Failure Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/errors.md Example of how to catch and log a ClashException when querying the tunnel state fails due to invalid JSON or deserialization errors. ```kotlin try { val state = Clash.queryTunnelState() } catch (e: ClashException) { Log.e("Clash", "Failed to query tunnel state: ${e.message}") // Assume offline mode or retry } ``` -------------------------------- ### Fallback Configuration Pattern Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/errors.md Loads a configuration profile, and if it fails, attempts to load a fallback profile. Throws an exception if both attempts fail. ```kotlin suspend fun loadConfigWithFallback( profileId: UUID, fallbackProfileId: UUID ) { try { profileManager.setActive( profileManager.queryByUUID(profileId) ?: throw FileNotFoundException("Profile not found") ) } catch (e: Exception) { Log.w("Config", "Primary load failed, trying fallback: ${e.message}") try { profileManager.setActive( profileManager.queryByUUID(fallbackProfileId) ?: throw FileNotFoundException("Fallback profile not found") ) } catch (fallbackError: Exception) { Log.e("Config", "Both loads failed", fallbackError) throw fallbackError } } } ``` -------------------------------- ### Query All Providers Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-manager-api.md Fetch a list of all configured providers. Each provider entry includes its name and type. ```kotlin val providers = clashManager.queryProviders() providers.forEach { provider -> println("${provider.name}: ${provider.type}") } ``` -------------------------------- ### queryAll Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/remote-service-api.md Queries and returns a list of all available profiles. ```APIDOC ## queryAll ### Description Queries all profiles. ### Method Suspend Function ### Endpoint N/A (SDK Method) ### Returns - **List** - All profiles ### Throws - **RemoteException** - on IPC failure ``` -------------------------------- ### IProfileManager.queryAll Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/remote-service-api.md Queries and retrieves all profiles managed by the service. Returns a list of all available profiles. ```APIDOC ## Function: queryAll ```kotlin fun queryAll(): List ``` Queries all profiles. **Returns:** `List` — List of all profiles **Throws:** `RemoteException` on IPC failure ``` -------------------------------- ### Native Function Declaration: nativeNotifyInstalledAppChanged Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Declares the external native function to notify the Clash core about changes in installed applications. It accepts a comma-separated string of 'uid:package' identifiers. ```kotlin external fun nativeNotifyInstalledAppChanged(uidList: String) ``` -------------------------------- ### Intent Handling Logic in ExternalControlActivity Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md The ExternalControlActivity handles various intent actions including ACTION_VIEW for profile import, and custom actions for starting, stopping, and toggling the Clash service. ```kotlin when(intent.action) { Intent.ACTION_VIEW -> { // Parse URL scheme, create profile, open properties } Intents.ACTION_TOGGLE_CLASH -> { // Check state and start or stop } Intents.ACTION_START_CLASH -> { // Start service (show error if already running) } Intents.ACTION_STOP_CLASH -> { // Stop service (show error if already stopped) } } ``` -------------------------------- ### Initialize ProfileManager Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/profile-manager-api.md Instantiate the ProfileManager with an Android Context. This is required for file and database access. ```kotlin val profileManager = ProfileManager(context) ``` -------------------------------- ### nativeLoad Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Loads a configuration file from a specified path asynchronously. The operation's completion is signaled via a CompletableDeferred. ```APIDOC ## nativeLoad ### Description Loads a configuration file from a specified path asynchronously. The operation's completion is signaled via a CompletableDeferred. ### Function Signature ```kotlin external fun nativeLoad( completable: CompletableDeferred, path: String ) ``` ### Parameters #### Query Parameters - **completable** (CompletableDeferred) - Required - Deferred to complete when done - **path** (String) - Required - File path ### Callback Completes or throws exception on deferred. ``` -------------------------------- ### AndroidManifest.xml URL Scheme Registration Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Register URL schemes in AndroidManifest.xml to handle profile imports and service control actions like starting, stopping, or toggling the Clash Meta service. ```xml ``` -------------------------------- ### Load Configuration File Asynchronously Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Loads a configuration file from a specified path asynchronously. The provided CompletableDeferred will be completed upon successful loading or throw an exception on failure. ```kotlin external fun nativeLoad( completable: CompletableDeferred, path: String ) ``` -------------------------------- ### Toggle Clash Service Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Toggles the state of the Clash service (start or stop) using a dedicated intent action. This provides a simple way to manage the service's running state. ```APIDOC ## Toggle Clash Service ### Description Toggles the state of the Clash service, starting it if it's stopped and stopping it if it's running. This action is useful for simple service management. ### Method `com.github.metacubex.clash.meta.action.TOGGLE_CLASH` ### Endpoint `com.github.metacubex.clash.meta/com.github.kr328.clash.ExternalControlActivity` ### Parameters None ### Request Example (Kotlin) ```kotlin fun toggleClash(context: Context) { val intent = Intent("com.github.metacubex.clash.meta.action.TOGGLE_CLASH") intent.setPackage("com.github.metacubex.clash.meta") context.startActivity(intent) } ``` ### Behavior - Starts the service if it is stopped. - Stops the service if it is running. - Shows appropriate toast messages for the action taken (e.g., "external_control_started", "external_control_stopped"). ``` -------------------------------- ### Initialize ClashManager Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-manager-api.md Instantiate the ClashManager with the Android context. This is the first step before using other ClashManager functionalities. ```kotlin val clashManager = ClashManager(context) ``` -------------------------------- ### Log Operation Completion (Info Level) Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/errors.md Use `Log.i` to log state changes and successful operation completion. ```kotlin Log.i("Component", "Operation completed successfully") ``` -------------------------------- ### Schedule Immediate Profile Update Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/profile-manager-api.md Schedules an immediate update for a profile, which involves fetching and committing the latest configuration. Use this to ensure a profile is up-to-date. ```kotlin profileManager.update(profileId) ``` -------------------------------- ### Accessing Files Directory Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/global-context.md Retrieves the application's private files directory and creates a subdirectory for clash. ```kotlin val filesDir = Global.application.filesDir val clashDir = filesDir.resolve("clash") ``` -------------------------------- ### URL Scheme for Profile Import Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md The clash:// and clashmeta:// URL schemes support importing profiles. Parameters like url, name, type, and update-interval can be appended as query parameters. ```text clash://install-config?url=&name=&type=&update-interval= clashmeta://install-config?url=&name=&type=&update-interval= ``` -------------------------------- ### IProfileManager.create Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/remote-service-api.md Creates a new profile with specified details. This function is asynchronous and returns the UUID of the newly created profile. ```APIDOC ## Suspend Function: create ```kotlin suspend fun create( type: Profile.Type, name: String, source: String = "", ageSecretKey: String? = null ): UUID ``` Creates a new profile. | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | type | Profile.Type | — | File, Url, or External | | name | String | — | Profile name | | source | String | "" | Source URL or path | | ageSecretKey | String? | null | Encryption key | **Returns:** `UUID` — New profile ID **Throws:** `RemoteException` on IPC failure ``` -------------------------------- ### queryAll Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/profile-manager-api.md Queries and retrieves a list of all profiles, including both imported and pending profiles. ```APIDOC ## Suspend Function: queryAll ```kotlin suspend fun queryAll(): List ``` ### Description Queries all profiles (both imported and pending). ### Returns: `List` - All profiles, ordered by import status and creation time ### Example: ```kotlin val profiles = profileManager.queryAll() println("Total profiles: ${profiles.size}") profiles.forEach { profile -> val status = if (profile.active) "[ACTIVE]" else "" println("$status ${profile.name}") } ``` ``` -------------------------------- ### Query All Providers Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Retrieves a list of all configured providers, including both proxy and rule providers. This is useful for inspecting the current state of your proxy and rule sources. ```kotlin fun queryProviders(): List ``` ```kotlin val providers = Clash.queryProviders() providers.forEach { provider -> println("${provider.name} (${provider.type})") println(" Vehicle: ${provider.vehicleType}") println(" Updated: ${Date(provider.updatedAt)}) } ``` -------------------------------- ### Kotlin Function: Import Profile with Interval Parameters Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/external-control.md Programmatically imports a profile using a clash://install-config URI. This function allows specifying the profile URL, a display name, and the update interval in minutes. ```kotlin fun importProfileWithInterval( context: Context, profileUrl: String, profileName: String, updateIntervalMinutes: Int ) { val encodedUrl = URLEncoder.encode(profileUrl, "UTF-8") val uri = Uri.parse("clash://install-config") .buildUpon() .appendQueryParameter("url", profileUrl) .appendQueryParameter("name", profileName) .appendQueryParameter("type", "url") .appendQueryParameter("update-interval", updateIntervalMinutes.toString()) .build() val intent = Intent(Intent.ACTION_VIEW, uri).apply { setPackage("com.github.metacubex.clash.meta") } context.startActivity(intent) } ``` -------------------------------- ### Create New Profile Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/profile-manager-api.md Create a new pending profile with specified type, name, source, and optional AGE encryption key. Returns the unique identifier for the newly created profile. ```kotlin val profileId = profileManager.create( type = Profile.Type.Url, name = "My Profile", source = "https://example.com/config.yaml" ) println("Created profile: $profileId") ``` -------------------------------- ### Define UiConfiguration Data Class Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/types.md Represents the current Clash configuration for UI display. It's a placeholder with fields handled dynamically. ```kotlin @Serializable class UiConfiguration : Parcelable ``` -------------------------------- ### queryConfiguration Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-manager-api.md Fetches the current Clash configuration settings. This operation may throw a ClashException on failure. ```APIDOC ## queryConfiguration ### Description Queries the current configuration. ### Method ``` fun queryConfiguration(): UiConfiguration ``` ### Returns `UiConfiguration` — Current configuration ### Throws `ClashException` on failure ### Example ```kotlin val config = clashManager.queryConfiguration() // Use for UI initialization ``` ``` -------------------------------- ### Accessing Resources Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/global-context.md Retrieves the application's resources to access strings, such as the app name. ```kotlin val resources = Global.application.resources val string = resources.getString(R.string.app_name) ``` -------------------------------- ### Query All Providers Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Queries all available providers and returns them as a JSON array of Provider objects. Includes provider name, type, and update information. ```kotlin external fun nativeQueryProviders(): String ``` -------------------------------- ### Query All Profiles Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/profile-manager-api.md Retrieves a list of all profiles, including both imported and pending ones. The profiles are ordered by import status and creation time. ```kotlin val profiles = profileManager.queryAll() println("Total profiles: ${profiles.size}") profiles.forEach { profile -> val status = if (profile.active) "[ACTIVE]" else "" println("$status ${profile.name}") } ``` -------------------------------- ### Clone Existing Profile Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/profile-manager-api.md Clone an existing profile to create a new pending profile. Handles potential FileNotFoundException if the source profile does not exist. ```kotlin try { val newId = profileManager.clone(existingProfileId) println("Cloned profile: $newId") } catch (e: FileNotFoundException) { println("Source profile not found") } ``` -------------------------------- ### commit Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/profile-manager-api.md Fetches a profile from its source, validates it, and commits it to imported storage. It supports progress observation via a callback. ```APIDOC ## Suspend Function: commit ```kotlin suspend fun commit( uuid: UUID, callback: IFetchObserver? = null ) ``` ### Description Fetches profile from source, validates, and commits to imported storage. ### Parameters #### Path Parameters - **uuid** (UUID) - Required - Profile UUID (pending or imported) - **callback** (IFetchObserver?) - Optional - Progress observer for fetch operation ### Side Effects: - Downloads configuration from source - Validates configuration format - Updates subscription metadata (upload, download, total, expire) - Moves from pending to imported on success - Broadcasts profile changed intent - Triggers auto-load if this is the active profile ### Progress Callbacks: The callback receives `FetchStatus` events: - `FetchConfiguration`: Fetching configuration file - `SubscriptionInfo`: Extracting subscription info - `FetchProviders`: Fetching providers - `Verifying`: Validating configuration ### Example: ```kotlin val observer = object : IFetchObserver { override fun updateStatus(status: FetchStatus) { println("${status.action}: ${status.progress}/${status.max}") } } try { profileManager.commit(profileId, observer) println("Profile committed successfully") } catch (e: ClashException) { println("Commit failed: ${e.message}") } ``` ``` -------------------------------- ### Configure Runtime Overrides Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/README.md Apply session-specific runtime configuration overrides. This allows temporary changes to ports, LAN access, and routing modes. ```kotlin val override = ConfigurationOverride( httpPort = 8080, allowLan = true, mode = TunnelState.Mode.Rule ) clashManager.patchOverride(Clash.OverrideSlot.Session, override) ``` -------------------------------- ### load Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Loads a configuration file into the Clash engine from a specified file path. The function returns a deferred object that completes when the loading process is finished. ```APIDOC ## Function: load ### Description Loads a configuration file into the Clash engine from a specified file path. The function returns a deferred object that completes when the loading process is finished. ### Signature ```kotlin fun load(path: File): CompletableDeferred ``` ### Parameters #### Path Parameters - **path** (File) - Required - Path to configuration file (YAML format) ### Returns `CompletableDeferred` — Deferred that completes when loading finishes ### Throws `ClashException` on loading failure (via exception completion) ### Example ```kotlin launch { try { Clash.load(File(configPath)).await() println("Configuration loaded") } catch (e: ClashException) { println("Failed to load config: ${e.message}") } } ``` ``` -------------------------------- ### Create New Profile Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/remote-service-api.md Creates a new profile with specified type, name, source, and optional encryption key. This is a suspend function. ```kotlin suspend fun create( type: Profile.Type, name: String, source: String = "", ageSecretKey: String? = null ): UUID ``` -------------------------------- ### fetchAndValid Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-core-api.md Fetches and validates a configuration from a URL. It saves the configuration to a specified file and provides progress reports via a callback. The function returns a deferred object that completes when the fetch operation is finished. ```APIDOC ## Function: fetchAndValid ### Description Fetches and validates a configuration from a URL. It saves the configuration to a specified file and provides progress reports via a callback. The function returns a deferred object that completes when the fetch operation is finished. ### Signature ```kotlin fun fetchAndValid( path: File, url: String, force: Boolean, reportStatus: (FetchStatus) -> Unit ): CompletableDeferred ``` ### Parameters #### Path Parameters - **path** (File) - Required - File to save configuration to - **url** (String) - Required - URL to fetch from - **force** (Boolean) - Required - If true, ignores cache and refetches - **reportStatus** (FetchStatus) -> Unit - Required - Callback for progress reports ### Returns `CompletableDeferred` — Deferred that completes when fetch finishes ### Throws `ClashException` on fetch/validation failure (via exception completion) ### Example ```kotlin launch { try { Clash.fetchAndValid( path = File(context.cacheDir, "profile.yaml"), url = "https://example.com/profile", force = true, reportStatus = { status -> println("Fetch progress: ${status.progress}/${status.max}") when (status.action) { FetchStatus.Action.FetchConfiguration -> println("Fetching config...") FetchStatus.Action.Verifying -> println("Verifying...") else -> {} } } ).await() println("Fetch completed successfully") } catch (e: ClashException) { println("Fetch failed: ${e.message}") } } ``` ``` -------------------------------- ### Query Proxies in a Group Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/clash-manager-api.md Retrieve detailed information about proxies within a specific group, sorted by delay. This helps in understanding available proxies and their performance. ```kotlin val group = clashManager.queryProxyGroup("PROXY", ProxySort.Delay) println("Selected proxy: ${group.now}") group.proxies.forEach { proxy -> println(" ${proxy.name}: ${proxy.delay}ms") } ``` -------------------------------- ### Query All Profiles Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/remote-service-api.md Retrieves a list of all profiles managed by the service. ```kotlin suspend fun queryAll(): List ``` -------------------------------- ### nativeFetchAndValid Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Fetches and validates a configuration from a given URL, saving it to a specified path. Supports forced refetching and provides progress updates via a callback. ```APIDOC ## nativeFetchAndValid ### Description Fetches and validates a configuration from a given URL, saving it to a specified path. Supports forced refetching and provides progress updates via a callback. ### Function Signature ```kotlin external fun nativeFetchAndValid( completable: FetchCallback, path: String, url: String, force: Boolean ) ``` ### Parameters #### Query Parameters - **completable** (FetchCallback) - Required - Callback for progress and completion - **path** (String) - Required - File path to save to - **url** (String) - Required - Source URL - **force** (Boolean) - Required - Force refetch, ignore cache ### Callbacks - `report(statusJson)`: Called with progress updates (FetchStatus as JSON) - `complete(error)`: Called on completion; error is null on success ``` -------------------------------- ### Query Current Configuration Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Call this function to retrieve the current configuration as a JSON string. It delegates to the config query mechanism. ```kotlin external fun nativeQueryConfiguration(): String ``` -------------------------------- ### nativeQueryProviders Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/api-reference/bridge-interface.md Queries all available providers and returns them as a JSON array. ```APIDOC ## nativeQueryProviders ### Description Queries all available providers and returns them as a JSON array. ### Function Signature ```kotlin external fun nativeQueryProviders(): String ``` ### Returns `String` — JSON array of Provider objects ### Format `[{"name":"provider1","type":"Proxy","vehicleType":"HTTP","updatedAt":0}]` ``` -------------------------------- ### Profile Manager API Reference Source: https://github.com/metacubex/clashmetaforandroid/blob/main/_autodocs/README.md Manages the lifecycle of profiles (configurations) with database persistence, including creation, cloning, deletion, updates, and activation. ```APIDOC ## Profile Manager API Reference Profile (configuration) lifecycle management with database persistence. ### Key Class `ProfileManager` in `com.github.kr328.clash.service` ### Functionality - Profile creation, cloning, and deletion - Profile metadata updates - Configuration fetch and validation - Profile activation and switching - Subscription metadata management ```