commit 017172f48a4f9fb1fb93e6d6642b38dc4d3118da Author: Giovanni Harting <539@idlegandalf.com> Date: Thu Dec 18 21:08:56 2025 +0100 Initial commit: Android Tether API app Exposes phone connection status via HTTP API for tethered devices. Features: - Auto-start/stop server when tethering is enabled/disabled - REST API with /status and /health endpoints - Connection type, signal strength, carrier, battery info - Foreground service with persistent notification Stack: Kotlin 2.3, AGP 8.13, Gradle 8.13, compileSdk 36 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9262b1e --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +*.iml +.gradle +/local.properties +/.idea +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties +/app/build +/app/release +*.apk +*.aab +*.jks +*.keystore diff --git a/README.md b/README.md new file mode 100644 index 0000000..a4f94ad --- /dev/null +++ b/README.md @@ -0,0 +1,194 @@ +# Tether API + +Android app that exposes your phone's connection status via HTTP API, accessible from tethered devices. + +## Features + +- **Auto-start on tether**: Server automatically starts/stops when tethering is enabled/disabled +- **Real-time status**: Connection type (5G/LTE/3G/WIFI), signal strength, carrier, battery level +- **Simple REST API**: JSON responses, easy to integrate with any client +- **No root required**: Works with standard Android permissions + +## Installation + +Build with Android Studio or use the release APK. + +**Required permissions:** +- `READ_PHONE_STATE` - Network connection type and carrier +- `ACCESS_FINE_LOCATION` - Required by Android 10+ for signal strength +- `POST_NOTIFICATIONS` - Service status notification + +## API Reference + +Default port: `8765` + +Common gateway IPs when tethering: +- USB tethering: `192.168.42.1` +- WiFi hotspot: `192.168.43.1` + +### GET /status + +Returns full phone status. + +**Response:** +```json +{ + "connection": { + "type": "LTE", + "signal_dbm": -89, + "signal_bars": 3, + "carrier": "T-Mobile", + "operator": "310260", + "roaming": false + }, + "battery": { + "level": 73, + "charging": false + }, + "network": { + "wifi_ssid": null, + "ip_addresses": ["192.168.42.129"] + }, + "timestamp": 1702915200 +} +``` + +**Fields:** + +| Field | Description | +|-------|-------------| +| `connection.type` | `5G`, `LTE`, `HSPA`, `3G`, `2G`, `WIFI`, `CELLULAR`, `NONE` | +| `connection.signal_dbm` | Signal strength in dBm (-999 if unavailable) | +| `connection.signal_bars` | 0-4 signal bars | +| `connection.carrier` | Network operator name | +| `connection.operator` | MCC+MNC code | +| `connection.roaming` | Whether roaming is active | +| `battery.level` | Battery percentage (0-100) | +| `battery.charging` | Whether device is charging | +| `network.wifi_ssid` | WiFi SSID if connected via WiFi | +| `network.ip_addresses` | List of device IP addresses | +| `timestamp` | Unix timestamp of response | + +### GET /health + +Health check endpoint. + +**Response:** +```json +{"status": "ok"} +``` + +### GET / + +API information. + +**Response:** +```json +{ + "name": "Tether API", + "version": "1.0.0", + "endpoints": [ + {"path": "/status", "method": "GET", "description": "Get phone status"}, + {"path": "/health", "method": "GET", "description": "Health check"} + ] +} +``` + +## Client Examples + +### Basic curl + +```bash +curl http://192.168.42.1:8765/status +``` + +### Auto-discover phone IP + +```bash +#!/bin/bash +for ip in 192.168.42.1 192.168.43.1 192.168.44.1; do + if curl -s --connect-timeout 1 "http://$ip:8765/health" | grep -q "ok"; then + echo "$ip" + exit 0 + fi +done +exit 1 +``` + +### Waybar module + +**~/.config/waybar/config:** +```json +{ + "custom/phone": { + "exec": "~/.local/bin/phone-status.sh", + "return-type": "json", + "interval": 10, + "format": "{}" + } +} +``` + +**~/.local/bin/phone-status.sh:** +```bash +#!/bin/bash +PHONE_IP="${PHONE_IP:-192.168.42.1}" +PORT="${PORT:-8765}" + +status=$(curl -s --connect-timeout 2 "http://$PHONE_IP:$PORT/status") +if [ -z "$status" ]; then + echo '{"text": "N/A", "tooltip": "Phone not connected", "class": "disconnected"}' + exit 0 +fi + +type=$(echo "$status" | jq -r '.connection.type') +bars=$(echo "$status" | jq -r '.connection.signal_bars') +battery=$(echo "$status" | jq -r '.battery.level') + +case $bars in + 4) signal="▂▄▆█" ;; + 3) signal="▂▄▆░" ;; + 2) signal="▂▄░░" ;; + 1) signal="▂░░░" ;; + *) signal="░░░░" ;; +esac + +echo "{\"text\": \"$type $signal $battery%\", \"tooltip\": \"$type | Signal: $bars/4 | Battery: $battery%\", \"class\": \"$type\"}" +``` + +### Python client + +```python +import requests + +def get_phone_status(ip="192.168.42.1", port=8765): + try: + r = requests.get(f"http://{ip}:{port}/status", timeout=2) + return r.json() + except: + return None + +status = get_phone_status() +if status: + print(f"Connection: {status['connection']['type']}") + print(f"Signal: {status['connection']['signal_bars']}/4") + print(f"Battery: {status['battery']['level']}%") +``` + +### KDE Plasmoid / Generic widget + +Most desktop widgets can execute shell commands. Use the curl/jq approach: + +```bash +curl -s http://192.168.42.1:8765/status | jq -r '"\(.connection.type) \(.connection.signal_bars)/4 \(.battery.level)%"' +``` + +## Building + +1. Open in Android Studio +2. Build > Build APK +3. Install APK on your phone + +## License + +MIT diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..93f2f78 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,61 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +android { + namespace = "dev.itsh.tetherapi" + compileSdk = 36 + + defaultConfig { + applicationId = "dev.itsh.tetherapi" + minSdk = 26 + targetSdk = 36 + versionCode = 1 + versionName = "1.0.0" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + } + + buildFeatures { + viewBinding = true + } +} + +kotlin { + compilerOptions { + jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21) + } +} + +dependencies { + implementation("androidx.core:core-ktx:1.17.0") + implementation("androidx.appcompat:appcompat:1.7.0") + implementation("com.google.android.material:material:1.12.0") + implementation("androidx.constraintlayout:constraintlayout:2.2.1") + + // NanoHTTPD for lightweight HTTP server + implementation("org.nanohttpd:nanohttpd:2.3.1") + + // Kotlin coroutines + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0") + + // JSON serialization + implementation("com.google.code.gson:gson:2.11.0") + + // Preferences for settings + implementation("androidx.preference:preference-ktx:1.2.1") +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..b4d16f4 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,8 @@ +# NanoHTTPD +-keep class fi.iki.elonen.** { *; } +-keep class org.nanohttpd.** { *; } + +# Gson +-keepattributes Signature +-keepattributes *Annotation* +-keep class dev.itsh.tetherapi.data.** { *; } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..744d5bf --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/dev/itsh/tetherapi/MainActivity.kt b/app/src/main/java/dev/itsh/tetherapi/MainActivity.kt new file mode 100644 index 0000000..278bb97 --- /dev/null +++ b/app/src/main/java/dev/itsh/tetherapi/MainActivity.kt @@ -0,0 +1,210 @@ +package dev.itsh.tetherapi + +import android.Manifest +import android.content.pm.PackageManager +import android.graphics.drawable.GradientDrawable +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.widget.Toast +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import androidx.preference.PreferenceManager +import com.google.gson.GsonBuilder +import dev.itsh.tetherapi.databinding.ActivityMainBinding +import dev.itsh.tetherapi.provider.StatusProvider +import dev.itsh.tetherapi.receiver.TetherStateReceiver +import dev.itsh.tetherapi.service.TetherApiService +import java.net.NetworkInterface + +class MainActivity : AppCompatActivity() { + + private lateinit var binding: ActivityMainBinding + private val handler = Handler(Looper.getMainLooper()) + private val statusProvider by lazy { StatusProvider(this) } + private val gson = GsonBuilder().setPrettyPrinting().create() + + private val requiredPermissions = buildList { + add(Manifest.permission.READ_PHONE_STATE) + add(Manifest.permission.ACCESS_FINE_LOCATION) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + add(Manifest.permission.POST_NOTIFICATIONS) + } + } + + private val permissionLauncher = registerForActivityResult( + ActivityResultContracts.RequestMultiplePermissions() + ) { permissions -> + val allGranted = permissions.all { it.value } + if (allGranted) { + updateUI() + } else { + showPermissionRationale() + } + } + + private val updateRunnable = object : Runnable { + override fun run() { + updateUI() + handler.postDelayed(this, UPDATE_INTERVAL) + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + + setupUI() + loadSettings() + checkPermissions() + } + + override fun onResume() { + super.onResume() + handler.post(updateRunnable) + } + + override fun onPause() { + super.onPause() + handler.removeCallbacks(updateRunnable) + } + + private fun setupUI() { + binding.toggleButton.setOnClickListener { + if (TetherApiService.isRunning) { + TetherApiService.stop(this) + } else { + val port = binding.portInput.text.toString().toIntOrNull() ?: TetherApiService.DEFAULT_PORT + TetherApiService.start(this, port) + } + handler.postDelayed({ updateUI() }, 500) + } + + binding.autoStartSwitch.setOnCheckedChangeListener { _, _ -> + saveSettings() + } + + binding.portInput.setOnFocusChangeListener { _, hasFocus -> + if (!hasFocus) { + saveSettings() + } + } + } + + private fun loadSettings() { + val prefs = PreferenceManager.getDefaultSharedPreferences(this) + binding.autoStartSwitch.isChecked = prefs.getBoolean(TetherStateReceiver.PREF_AUTO_START, true) + binding.portInput.setText(prefs.getInt(TetherStateReceiver.PREF_PORT, TetherApiService.DEFAULT_PORT).toString()) + } + + private fun saveSettings() { + val prefs = PreferenceManager.getDefaultSharedPreferences(this) + val port = binding.portInput.text.toString().toIntOrNull() ?: TetherApiService.DEFAULT_PORT + prefs.edit() + .putBoolean(TetherStateReceiver.PREF_AUTO_START, binding.autoStartSwitch.isChecked) + .putInt(TetherStateReceiver.PREF_PORT, port) + .apply() + } + + private fun checkPermissions() { + val missingPermissions = requiredPermissions.filter { + ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED + } + + if (missingPermissions.isNotEmpty()) { + permissionLauncher.launch(missingPermissions.toTypedArray()) + } + } + + private fun showPermissionRationale() { + AlertDialog.Builder(this) + .setTitle("Permissions Required") + .setMessage( + "This app needs the following permissions:\n\n" + + "• Phone State: To read network connection type and carrier\n" + + "• Location: Required by Android to access cell signal info\n" + + "• Notifications: To show service status" + ) + .setPositiveButton("Grant") { _, _ -> + permissionLauncher.launch(requiredPermissions.toTypedArray()) + } + .setNegativeButton("Cancel", null) + .show() + } + + private fun updateUI() { + val isRunning = TetherApiService.isRunning + val port = TetherApiService.currentPort ?: binding.portInput.text.toString().toIntOrNull() ?: TetherApiService.DEFAULT_PORT + + binding.statusText.text = if (isRunning) { + getString(R.string.status_running) + } else { + getString(R.string.status_stopped) + } + + val statusColor = if (isRunning) { + ContextCompat.getColor(this, R.color.status_running) + } else { + ContextCompat.getColor(this, R.color.status_stopped) + } + (binding.statusIndicator.background as? GradientDrawable)?.setColor(statusColor) + + binding.toggleButton.text = if (isRunning) { + getString(R.string.btn_stop) + } else { + getString(R.string.btn_start) + } + + val gatewayIp = getGatewayIp() + binding.endpointText.text = if (gatewayIp != null) { + "http://$gatewayIp:$port/status" + } else { + "http://[phone-ip]:$port/status" + } + + updateStatusPreview() + } + + private fun updateStatusPreview() { + try { + val status = statusProvider.getStatus() + binding.previewText.text = gson.toJson(status) + } catch (e: Exception) { + binding.previewText.text = "Error: ${e.message}" + } + } + + private fun getGatewayIp(): String? { + try { + val interfaces = NetworkInterface.getNetworkInterfaces() + while (interfaces.hasMoreElements()) { + val networkInterface = interfaces.nextElement() + val name = networkInterface.name.lowercase() + + if (name.startsWith("rndis") || name.startsWith("usb") || + name.startsWith("wlan") || name.startsWith("ap") || + name.startsWith("swlan")) { + + val addresses = networkInterface.inetAddresses + while (addresses.hasMoreElements()) { + val address = addresses.nextElement() + if (!address.isLoopbackAddress && address.hostAddress?.contains(".") == true) { + return address.hostAddress + } + } + } + } + } catch (e: Exception) { + // Ignore + } + return null + } + + companion object { + private const val UPDATE_INTERVAL = 2000L + } +} diff --git a/app/src/main/java/dev/itsh/tetherapi/api/ApiServer.kt b/app/src/main/java/dev/itsh/tetherapi/api/ApiServer.kt new file mode 100644 index 0000000..bc730df --- /dev/null +++ b/app/src/main/java/dev/itsh/tetherapi/api/ApiServer.kt @@ -0,0 +1,88 @@ +package dev.itsh.tetherapi.api + +import android.content.Context +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import dev.itsh.tetherapi.provider.StatusProvider +import fi.iki.elonen.NanoHTTPD + +class ApiServer( + private val context: Context, + port: Int +) : NanoHTTPD("0.0.0.0", port) { + + private val statusProvider = StatusProvider(context) + private val gson: Gson = GsonBuilder() + .setPrettyPrinting() + .create() + + override fun serve(session: IHTTPSession): Response { + val uri = session.uri + val method = session.method + + if (method != Method.GET) { + return newFixedLengthResponse( + Response.Status.METHOD_NOT_ALLOWED, + MIME_JSON, + """{"error": "Method not allowed"}""" + ).apply { + addHeader("Access-Control-Allow-Origin", "*") + } + } + + return when (uri) { + "/status" -> handleStatus() + "/health" -> handleHealth() + "/" -> handleRoot() + else -> handleNotFound() + } + } + + private fun handleStatus(): Response { + return try { + val status = statusProvider.getStatus() + val json = gson.toJson(status) + jsonResponse(Response.Status.OK, json) + } catch (e: Exception) { + jsonResponse( + Response.Status.INTERNAL_ERROR, + """{"error": "${e.message ?: "Unknown error"}"}""" + ) + } + } + + private fun handleHealth(): Response { + return jsonResponse(Response.Status.OK, """{"status": "ok"}""") + } + + private fun handleRoot(): Response { + val info = mapOf( + "name" to "Tether API", + "version" to "1.0.0", + "endpoints" to listOf( + mapOf("path" to "/status", "method" to "GET", "description" to "Get phone status"), + mapOf("path" to "/health", "method" to "GET", "description" to "Health check") + ) + ) + return jsonResponse(Response.Status.OK, gson.toJson(info)) + } + + private fun handleNotFound(): Response { + return jsonResponse( + Response.Status.NOT_FOUND, + """{"error": "Not found"}""" + ) + } + + private fun jsonResponse(status: Response.Status, json: String): Response { + return newFixedLengthResponse(status, MIME_JSON, json).apply { + addHeader("Access-Control-Allow-Origin", "*") + addHeader("Access-Control-Allow-Methods", "GET") + addHeader("Cache-Control", "no-cache") + } + } + + companion object { + private const val MIME_JSON = "application/json" + } +} diff --git a/app/src/main/java/dev/itsh/tetherapi/data/PhoneStatus.kt b/app/src/main/java/dev/itsh/tetherapi/data/PhoneStatus.kt new file mode 100644 index 0000000..2a1abf3 --- /dev/null +++ b/app/src/main/java/dev/itsh/tetherapi/data/PhoneStatus.kt @@ -0,0 +1,33 @@ +package dev.itsh.tetherapi.data + +import com.google.gson.annotations.SerializedName + +data class PhoneStatus( + val connection: ConnectionInfo, + val battery: BatteryInfo, + val network: NetworkInfo, + val timestamp: Long +) + +data class ConnectionInfo( + val type: String, + @SerializedName("signal_dbm") + val signalDbm: Int, + @SerializedName("signal_bars") + val signalBars: Int, + val carrier: String, + val operator: String, + val roaming: Boolean +) + +data class BatteryInfo( + val level: Int, + val charging: Boolean +) + +data class NetworkInfo( + @SerializedName("wifi_ssid") + val wifiSsid: String?, + @SerializedName("ip_addresses") + val ipAddresses: List +) diff --git a/app/src/main/java/dev/itsh/tetherapi/provider/StatusProvider.kt b/app/src/main/java/dev/itsh/tetherapi/provider/StatusProvider.kt new file mode 100644 index 0000000..2c55f8c --- /dev/null +++ b/app/src/main/java/dev/itsh/tetherapi/provider/StatusProvider.kt @@ -0,0 +1,255 @@ +package dev.itsh.tetherapi.provider + +import android.Manifest +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.pm.PackageManager +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.wifi.WifiManager +import android.os.BatteryManager +import android.os.Build +import android.telephony.CellInfo +import android.telephony.CellInfoLte +import android.telephony.CellInfoNr +import android.telephony.CellInfoGsm +import android.telephony.CellInfoWcdma +import android.telephony.CellInfoCdma +import android.telephony.TelephonyManager +import androidx.core.content.ContextCompat +import dev.itsh.tetherapi.data.BatteryInfo +import dev.itsh.tetherapi.data.ConnectionInfo +import dev.itsh.tetherapi.data.NetworkInfo +import dev.itsh.tetherapi.data.PhoneStatus +import java.net.NetworkInterface + +class StatusProvider(private val context: Context) { + + private val telephonyManager: TelephonyManager by lazy { + context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + } + + private val connectivityManager: ConnectivityManager by lazy { + context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + } + + private val wifiManager: WifiManager by lazy { + context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager + } + + fun getStatus(): PhoneStatus { + return PhoneStatus( + connection = getConnectionInfo(), + battery = getBatteryInfo(), + network = getNetworkInfo(), + timestamp = System.currentTimeMillis() / 1000 + ) + } + + private fun getConnectionInfo(): ConnectionInfo { + val hasPhonePermission = ContextCompat.checkSelfPermission( + context, Manifest.permission.READ_PHONE_STATE + ) == PackageManager.PERMISSION_GRANTED + + val hasLocationPermission = ContextCompat.checkSelfPermission( + context, Manifest.permission.ACCESS_FINE_LOCATION + ) == PackageManager.PERMISSION_GRANTED + + val connectionType = getConnectionType() + val (signalDbm, signalBars) = if (hasLocationPermission) { + getSignalStrength() + } else { + Pair(-999, 0) + } + + val carrier = if (hasPhonePermission) { + telephonyManager.networkOperatorName ?: "Unknown" + } else { + "Unknown" + } + + val operator = telephonyManager.networkOperator ?: "" + + val isRoaming = try { + telephonyManager.isNetworkRoaming + } catch (e: Exception) { + false + } + + return ConnectionInfo( + type = connectionType, + signalDbm = signalDbm, + signalBars = signalBars, + carrier = carrier, + operator = operator, + roaming = isRoaming + ) + } + + private fun getConnectionType(): String { + val network = connectivityManager.activeNetwork ?: return "NONE" + val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return "NONE" + + return when { + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "WIFI" + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> getCellularType() + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "ETHERNET" + else -> "UNKNOWN" + } + } + + private fun getCellularType(): String { + val hasPermission = ContextCompat.checkSelfPermission( + context, Manifest.permission.READ_PHONE_STATE + ) == PackageManager.PERMISSION_GRANTED + + if (!hasPermission) return "CELLULAR" + + return when (telephonyManager.dataNetworkType) { + TelephonyManager.NETWORK_TYPE_NR -> "5G" + TelephonyManager.NETWORK_TYPE_LTE -> "LTE" + TelephonyManager.NETWORK_TYPE_HSPAP, + TelephonyManager.NETWORK_TYPE_HSPA, + TelephonyManager.NETWORK_TYPE_HSDPA, + TelephonyManager.NETWORK_TYPE_HSUPA -> "HSPA" + TelephonyManager.NETWORK_TYPE_UMTS, + TelephonyManager.NETWORK_TYPE_EVDO_0, + TelephonyManager.NETWORK_TYPE_EVDO_A, + TelephonyManager.NETWORK_TYPE_EVDO_B -> "3G" + TelephonyManager.NETWORK_TYPE_EDGE, + TelephonyManager.NETWORK_TYPE_GPRS, + TelephonyManager.NETWORK_TYPE_CDMA, + TelephonyManager.NETWORK_TYPE_1xRTT -> "2G" + TelephonyManager.NETWORK_TYPE_UNKNOWN -> "CELLULAR" + else -> "CELLULAR" + } + } + + @Suppress("DEPRECATION") + private fun getSignalStrength(): Pair { + val hasLocationPermission = ContextCompat.checkSelfPermission( + context, Manifest.permission.ACCESS_FINE_LOCATION + ) == PackageManager.PERMISSION_GRANTED + + if (!hasLocationPermission) { + return Pair(-999, 0) + } + + try { + val cellInfoList: List? = telephonyManager.allCellInfo + if (cellInfoList.isNullOrEmpty()) { + return Pair(-999, 0) + } + + for (cellInfo in cellInfoList) { + if (!cellInfo.isRegistered) continue + + val dbm = when (cellInfo) { + is CellInfoLte -> cellInfo.cellSignalStrength.dbm + is CellInfoNr -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + cellInfo.cellSignalStrength.dbm + } else -999 + is CellInfoGsm -> cellInfo.cellSignalStrength.dbm + is CellInfoWcdma -> cellInfo.cellSignalStrength.dbm + is CellInfoCdma -> cellInfo.cellSignalStrength.dbm + else -> continue + } + + val level = when (cellInfo) { + is CellInfoLte -> cellInfo.cellSignalStrength.level + is CellInfoNr -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + cellInfo.cellSignalStrength.level + } else 0 + is CellInfoGsm -> cellInfo.cellSignalStrength.level + is CellInfoWcdma -> cellInfo.cellSignalStrength.level + is CellInfoCdma -> cellInfo.cellSignalStrength.level + else -> continue + } + + return Pair(dbm, level) + } + } catch (e: SecurityException) { + return Pair(-999, 0) + } catch (e: Exception) { + return Pair(-999, 0) + } + + return Pair(-999, 0) + } + + private fun getBatteryInfo(): BatteryInfo { + val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { filter -> + context.registerReceiver(null, filter) + } + + val level = batteryStatus?.let { intent -> + val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) + val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) + if (level >= 0 && scale > 0) { + (level * 100 / scale) + } else { + -1 + } + } ?: -1 + + val isCharging = batteryStatus?.let { intent -> + val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1) + status == BatteryManager.BATTERY_STATUS_CHARGING || + status == BatteryManager.BATTERY_STATUS_FULL + } ?: false + + return BatteryInfo( + level = level, + charging = isCharging + ) + } + + @Suppress("DEPRECATION") + private fun getNetworkInfo(): NetworkInfo { + val wifiSsid = try { + val network = connectivityManager.activeNetwork + val capabilities = connectivityManager.getNetworkCapabilities(network) + if (capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true) { + val wifiInfo = wifiManager.connectionInfo + wifiInfo?.ssid?.replace("\"", "")?.takeIf { it != "" } + } else { + null + } + } catch (e: Exception) { + null + } + + val ipAddresses = getIpAddresses() + + return NetworkInfo( + wifiSsid = wifiSsid, + ipAddresses = ipAddresses + ) + } + + private fun getIpAddresses(): List { + val addresses = mutableListOf() + try { + val interfaces = NetworkInterface.getNetworkInterfaces() + while (interfaces.hasMoreElements()) { + val networkInterface = interfaces.nextElement() + if (networkInterface.isLoopback || !networkInterface.isUp) continue + + val inetAddresses = networkInterface.inetAddresses + while (inetAddresses.hasMoreElements()) { + val address = inetAddresses.nextElement() + if (!address.isLoopbackAddress && !address.hostAddress.isNullOrEmpty()) { + val hostAddress = address.hostAddress!! + if (!hostAddress.contains(":")) { + addresses.add(hostAddress) + } + } + } + } + } catch (e: Exception) { + // Ignore + } + return addresses + } +} diff --git a/app/src/main/java/dev/itsh/tetherapi/receiver/TetherStateReceiver.kt b/app/src/main/java/dev/itsh/tetherapi/receiver/TetherStateReceiver.kt new file mode 100644 index 0000000..9941e02 --- /dev/null +++ b/app/src/main/java/dev/itsh/tetherapi/receiver/TetherStateReceiver.kt @@ -0,0 +1,61 @@ +package dev.itsh.tetherapi.receiver + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.net.ConnectivityManager +import android.os.Build +import androidx.preference.PreferenceManager +import dev.itsh.tetherapi.service.TetherApiService + +class TetherStateReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != ACTION_TETHER_STATE_CHANGED) return + + val prefs = PreferenceManager.getDefaultSharedPreferences(context) + val autoStartEnabled = prefs.getBoolean(PREF_AUTO_START, true) + + if (!autoStartEnabled) return + + val isTethering = isTetherActive(context, intent) + val port = prefs.getInt(PREF_PORT, TetherApiService.DEFAULT_PORT) + + if (isTethering && !TetherApiService.isRunning) { + TetherApiService.start(context, port) + } else if (!isTethering && TetherApiService.isRunning) { + TetherApiService.stop(context) + } + } + + @Suppress("DEPRECATION") + private fun isTetherActive(context: Context, intent: Intent): Boolean { + val extras = intent.extras ?: return false + + val activeList = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + extras.getStringArrayList("activeArray") + } else { + @Suppress("UNCHECKED_CAST") + extras.get("activeArray") as? ArrayList + } + + if (!activeList.isNullOrEmpty()) { + return true + } + + return try { + val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + val method = cm.javaClass.getDeclaredMethod("getTetheredIfaces") + val tetheredIfaces = method.invoke(cm) as? Array<*> + tetheredIfaces != null && tetheredIfaces.isNotEmpty() + } catch (e: Exception) { + false + } + } + + companion object { + const val ACTION_TETHER_STATE_CHANGED = "android.net.conn.TETHER_STATE_CHANGED" + const val PREF_AUTO_START = "auto_start_on_tether" + const val PREF_PORT = "api_port" + } +} diff --git a/app/src/main/java/dev/itsh/tetherapi/service/TetherApiService.kt b/app/src/main/java/dev/itsh/tetherapi/service/TetherApiService.kt new file mode 100644 index 0000000..44149c2 --- /dev/null +++ b/app/src/main/java/dev/itsh/tetherapi/service/TetherApiService.kt @@ -0,0 +1,163 @@ +package dev.itsh.tetherapi.service + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.os.Binder +import android.os.Build +import android.os.IBinder +import androidx.core.app.NotificationCompat +import dev.itsh.tetherapi.MainActivity +import dev.itsh.tetherapi.R +import dev.itsh.tetherapi.api.ApiServer + +class TetherApiService : Service() { + + private var apiServer: ApiServer? = null + private val binder = LocalBinder() + + inner class LocalBinder : Binder() { + fun getService(): TetherApiService = this@TetherApiService + } + + override fun onBind(intent: Intent?): IBinder = binder + + override fun onCreate() { + super.onCreate() + createNotificationChannel() + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + val port = intent?.getIntExtra(EXTRA_PORT, DEFAULT_PORT) ?: DEFAULT_PORT + + when (intent?.action) { + ACTION_START -> startServer(port) + ACTION_STOP -> stopServer() + } + + return START_STICKY + } + + private fun startServer(port: Int) { + if (apiServer?.isAlive == true) { + return + } + + try { + apiServer = ApiServer(this, port).apply { + start() + } + + val notification = createNotification(port) + startForeground(NOTIFICATION_ID, notification) + + isRunning = true + currentPort = port + } catch (e: Exception) { + stopSelf() + } + } + + private fun stopServer() { + apiServer?.stop() + apiServer = null + isRunning = false + currentPort = null + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + } + + override fun onDestroy() { + stopServer() + super.onDestroy() + } + + private fun createNotificationChannel() { + val channel = NotificationChannel( + CHANNEL_ID, + getString(R.string.service_notification_channel), + NotificationManager.IMPORTANCE_LOW + ).apply { + description = "Shows when Tether API server is running" + setShowBadge(false) + } + + val notificationManager = getSystemService(NotificationManager::class.java) + notificationManager.createNotificationChannel(channel) + } + + private fun createNotification(port: Int): Notification { + val intent = Intent(this, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_SINGLE_TOP + } + + val pendingIntent = PendingIntent.getActivity( + this, + 0, + intent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + + val stopIntent = Intent(this, TetherApiService::class.java).apply { + action = ACTION_STOP + } + + val stopPendingIntent = PendingIntent.getService( + this, + 1, + stopIntent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + + return NotificationCompat.Builder(this, CHANNEL_ID) + .setContentTitle(getString(R.string.service_notification_title)) + .setContentText(getString(R.string.service_notification_text, port)) + .setSmallIcon(R.drawable.ic_notification) + .setContentIntent(pendingIntent) + .addAction(0, "Stop", stopPendingIntent) + .setOngoing(true) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setCategory(NotificationCompat.CATEGORY_SERVICE) + .build() + } + + companion object { + const val ACTION_START = "dev.itsh.tetherapi.action.START" + const val ACTION_STOP = "dev.itsh.tetherapi.action.STOP" + const val EXTRA_PORT = "dev.itsh.tetherapi.extra.PORT" + const val DEFAULT_PORT = 8765 + + private const val CHANNEL_ID = "tether_api_service" + private const val NOTIFICATION_ID = 1 + + var isRunning = false + private set + + var currentPort: Int? = null + private set + + fun start(context: Context, port: Int = DEFAULT_PORT) { + val intent = Intent(context, TetherApiService::class.java).apply { + action = ACTION_START + putExtra(EXTRA_PORT, port) + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + context.startForegroundService(intent) + } else { + context.startService(intent) + } + } + + fun stop(context: Context) { + val intent = Intent(context, TetherApiService::class.java).apply { + action = ACTION_STOP + } + context.startService(intent) + } + } +} diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..7738df9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_notification.xml b/app/src/main/res/drawable/ic_notification.xml new file mode 100644 index 0000000..9d6cda0 --- /dev/null +++ b/app/src/main/res/drawable/ic_notification.xml @@ -0,0 +1,24 @@ + + + + + + + + + + diff --git a/app/src/main/res/drawable/status_indicator.xml b/app/src/main/res/drawable/status_indicator.xml new file mode 100644 index 0000000..2ce56aa --- /dev/null +++ b/app/src/main/res/drawable/status_indicator.xml @@ -0,0 +1,5 @@ + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..417941c --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,177 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..a8b92c6 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..a8b92c6 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..cbcb603 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,16 @@ + + + #1976D2 + #1565C0 + #26A69A + #FAFAFA + #FFFFFF + #B00020 + #FFFFFF + #000000 + #000000 + #000000 + #FFFFFF + #4CAF50 + #9E9E9E + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..93b95e0 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,17 @@ + + + Tether API + Tether API Service + Tether API Running + API server active on port %d + Running + Stopped + Start Server + Stop Server + API Endpoint + Port + Auto-start on tether + Location permission is required to access cell signal information on Android 10+ + Phone state permission is required to read network connection information + Notification permission allows showing the service status + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..5f4ebb7 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,16 @@ + + + + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..c14ed1f --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "8.13.0" apply false + id("org.jetbrains.kotlin.android") version "2.3.0" apply false +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..f0a2e55 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +android.useAndroidX=true +kotlin.code.style=official +android.nonTransitiveRClass=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..37f853b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..adff685 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e509b2d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..a95ac20 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "TetherAPI" +include(":app")