# PrivacyPin Minimal — Full Session Dump > This file contains everything needed to understand and continue this project from scratch. > Created after a successful implementation session where background location was fully tested. --- ## TL;DR This is a native Kotlin Android app that runs a **foreground service** to continuously track GPS location every 60 seconds and POST it to a server. It works without Google Play Services (designed for GrapheneOS). It survives: app swiped from recents, process killed by system, and device reboots. --- ## Project: PrivacyPin **What:** Self-hosted federated location sharing app **Repo:** https://github.com/azomDev/PrivacyPin **This directory:** Minimal standalone implementation of the hardest part — reliable background location on Android without Play Services. --- ## Environment (100% local, nothing system-wide) | What | Where | |------|-------| | Android SDK | `~/android-sdk/` | | JDK 21 (Temurin) | `~/android-sdk/jdk/jdk-21.0.7+6/` | | SDK tools | `~/android-sdk/cmdline-tools/latest/bin/` | | Platform tools (adb) | `~/android-sdk/platform-tools/` | | Emulator | `~/android-sdk/emulator/` | | System image | `android-35;default;x86_64` (NO Play Services) | | AVD | `privacypin_test` (Pixel 6, API 35) | | AVD data | `~/.android/avd/privacypin_test.avd/` | **To set up shell:** `source android_env.sh` (sets JAVA_HOME, ANDROID_HOME, PATH) **To nuke everything:** `rm -rf ~/android-sdk ~/.android` **OS:** CachyOS (Arch-based Linux) --- ## Versions | Component | Version | |-----------|---------| | JDK | 21 (Temurin 21.0.7+6) | | Kotlin | 2.3.21 | | AGP | 8.7.3 | | Gradle | 8.11.1 (wrapper) | | compileSdk | 35 | | targetSdk | 35 | | minSdk | 26 | | Build tools | 35.0.0 | **Note:** Kotlin 2.3.x removed `kotlinOptions` DSL — must use `kotlin { compilerOptions { ... } }` instead. --- ## Project Structure ``` pp-minimal/ ├── android_env.sh # Shell env setup (source this first) ├── AGENT_CONTEXT.md # Shorter context doc ├── SESSION_DUMP.md # THIS FILE ├── build.gradle.kts # Root: plugin versions ├── settings.gradle.kts # Module config ├── gradle.properties # JVM args, AndroidX ├── gradlew # Gradle wrapper script ├── gradle/wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties # Points to Gradle 8.11.1 ├── app/ │ ├── build.gradle.kts # App module: deps, SDK config │ └── src/main/ │ ├── AndroidManifest.xml # Permissions + service + boot receiver │ ├── java/dev/azom/privacypin/ │ │ ├── MainActivity.kt # UI + permission flow │ │ ├── LocationService.kt # Foreground service + GPS + HTTP POST │ │ └── BootReceiver.kt # Auto-restart on boot │ └── res/ │ ├── layout/activity_main.xml # Toggle button + location display │ └── values/ │ ├── strings.xml │ └── themes.xml └── tools/ ├── build_and_deploy.sh # Build + install + launch ├── logcat.sh # Filtered logs by PID/tag ├── check_permissions.sh # Show permission states ├── grant_permissions.sh # Grant all perms via ADB ├── mock_location.sh # Send fake GPS to emulator ├── check_service.sh # Is service alive? Notifications? ├── emulator_start.sh # Boot emulator headlessly ├── emulator_stop.sh # Kill emulator ├── full_reset.sh # Uninstall + clean + redeploy ├── start_test_server.sh # Start Python HTTP server (bg) └── test_server.py # Python test server on port 8080 ``` --- ## How It Works ### Architecture ``` ┌─────────────────────┐ broadcast ┌─────────────────────┐ │ MainActivity │◄─────────────────────│ LocationService │ │ (UI + permissions) │ │ (foreground svc) │ └─────────────────────┘ ├─────────────────────┤ │ LocationManager GPS │ │ every 60s, 0m min │ ├─────────────────────┤ │ HTTP POST to server │ │ on each location │ └──────────┬──────────┘ │ ┌──────────▼──────────┐ │ Server :8080 │ │ POST /location │ └─────────────────────┘ ``` ### Permission Flow (in order) 1. `ACCESS_FINE_LOCATION` + `ACCESS_COARSE_LOCATION` (requested together) 2. `ACCESS_BACKGROUND_LOCATION` (MUST be separate, API 29+) 3. `POST_NOTIFICATIONS` (API 33+) 4. Then service starts ### Survival Mechanisms - **Swipe from recents:** Foreground service with notification keeps process alive - **System kill (OOM):** `START_STICKY` makes Android restart the service - **Reboot:** `BootReceiver` listens for `BOOT_COMPLETED`, checks SharedPreferences, restarts service if it was running ### Server Communication - HTTP POST to `http://10.0.2.2:8080/location` (10.0.2.2 = host localhost from emulator) - JSON payload: `{"lat":48.8566,"lon":2.3522,"accuracy":5.0,"timestamp":1747696485000}` - Uses `HttpURLConnection` (built into Android, no deps) - Runs on a background thread per request - 5s connect/read timeout, errors logged but don't crash service --- ## Test Results (all passing) | Scenario | Result | |----------|--------| | App swiped from recents | ✅ Service keeps running | | Process killed (kill -9) | ✅ Auto-restarts (START_STICKY) | | Device reboot | ✅ Auto-restarts (BootReceiver) | | Screen off | ✅ Keeps getting + posting locations | | App in background | ✅ Keeps getting + posting locations | | Mock GPS → server | ✅ Full end-to-end verified | --- ## Key Files Content ### android_env.sh ``` #!/bin/sh export JAVA_HOME=/home/azom/android-sdk/jdk/jdk-21.0.7+6 export ANDROID_HOME=/home/azom/android-sdk export PATH=$JAVA_HOME/bin:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH ``` ### build.gradle.kts (root) ``` plugins { id("com.android.application") version "8.7.3" apply false id("org.jetbrains.kotlin.android") version "2.3.21" apply false } ``` ### app/build.gradle.kts ``` plugins { id("com.android.application") id("org.jetbrains.kotlin.android") } android { namespace = "dev.azom.privacypin" compileSdk = 35 defaultConfig { applicationId = "dev.azom.privacypin" minSdk = 26 targetSdk = 35 versionCode = 1 versionName = "1.0" } buildTypes { release { isMinifyEnabled = false } } compileOptions { sourceCompatibility = JavaVersion.VERSION_21 targetCompatibility = JavaVersion.VERSION_21 } } kotlin { compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21) } } dependencies { implementation("androidx.appcompat:appcompat:1.7.0") implementation("androidx.core:core-ktx:1.15.0") implementation("androidx.activity:activity-ktx:1.9.0") } ``` ### AndroidManifest.xml ``` ``` ### LocationService.kt ``` package dev.azom.privacypin import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Build import android.os.IBinder import android.util.Log import java.io.OutputStreamWriter import java.net.HttpURLConnection import java.net.URL import kotlin.concurrent.thread class LocationService : Service(), LocationListener { companion object { private const val TAG = "PrivacyPin" private const val NOTIFICATION_ID = 1 private const val CHANNEL_ID = "privacypin_location_channel" const val ACTION_LOCATION_UPDATE = "dev.azom.privacypin.LOCATION_UPDATE" const val EXTRA_LATITUDE = "latitude" const val EXTRA_LONGITUDE = "longitude" private const val LOCATION_INTERVAL_MS = 60000L private const val LOCATION_MIN_DISTANCE_M = 0f private const val SERVER_URL = "http://10.0.2.2:8080/location" } private lateinit var locationManager: LocationManager override fun onCreate() { super.onCreate() Log.d(TAG, "LocationService onCreate") locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Log.d(TAG, "LocationService onStartCommand") getSharedPreferences("privacypin_prefs", Context.MODE_PRIVATE) .edit().putBoolean("service_running", true).apply() startForegroundWithNotification() startLocationUpdates() return START_STICKY } override fun onBind(intent: Intent?): IBinder? = null override fun onDestroy() { Log.d(TAG, "LocationService onDestroy") stopLocationUpdates() getSharedPreferences("privacypin_prefs", Context.MODE_PRIVATE) .edit().putBoolean("service_running", false).apply() super.onDestroy() } override fun onLocationChanged(location: Location) { Log.i(TAG, "Location update: lat=${location.latitude}, lon=${location.longitude}, " + "accuracy=${location.accuracy}m, provider=${location.provider}") val intent = Intent(ACTION_LOCATION_UPDATE).apply { setPackage(packageName) putExtra(EXTRA_LATITUDE, location.latitude) putExtra(EXTRA_LONGITUDE, location.longitude) } sendBroadcast(intent) sendToServer(location.latitude, location.longitude, location.accuracy, location.time) } override fun onProviderEnabled(provider: String) { Log.d(TAG, "Provider enabled: $provider") } override fun onProviderDisabled(provider: String) { Log.w(TAG, "Provider disabled: $provider") } private fun sendToServer(lat: Double, lon: Double, accuracy: Float, timestamp: Long) { thread { try { val url = URL(SERVER_URL) val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "POST" connection.setRequestProperty("Content-Type", "application/json") connection.doOutput = true connection.connectTimeout = 5000 connection.readTimeout = 5000 val json = """{"lat":$lat,"lon":$lon,"accuracy":$accuracy,"timestamp":$timestamp}""" val writer = OutputStreamWriter(connection.outputStream) writer.write(json) writer.flush() writer.close() val responseCode = connection.responseCode if (responseCode == 200) { Log.d(TAG, "Server POST success") } else { Log.w(TAG, "Server POST failed: HTTP $responseCode") } connection.disconnect() } catch (e: Exception) { Log.e(TAG, "Server POST error: ${e.message}") } } } private fun startForegroundWithNotification() { createNotificationChannel() val notification = Notification.Builder(this, CHANNEL_ID) .setContentTitle("PrivacyPin") .setContentText("Sharing location") .setSmallIcon(android.R.drawable.ic_menu_mylocation) .setOngoing(true) .build() if (Build.VERSION.SDK_INT >= 34) { startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION) } else { startForeground(NOTIFICATION_ID, notification) } Log.d(TAG, "Foreground notification posted") } private fun createNotificationChannel() { val channel = NotificationChannel( CHANNEL_ID, "Location Sharing", NotificationManager.IMPORTANCE_LOW ).apply { description = "Notification shown while PrivacyPin is sharing your location" } val manager = getSystemService(NotificationManager::class.java) manager.createNotificationChannel(channel) } @Suppress("MissingPermission") private fun startLocationUpdates() { val providers = locationManager.getProviders(true) Log.d(TAG, "Available location providers: $providers") if (providers.contains(LocationManager.GPS_PROVIDER)) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_INTERVAL_MS, LOCATION_MIN_DISTANCE_M, this ) Log.d(TAG, "Registered for GPS updates") } if (providers.contains(LocationManager.NETWORK_PROVIDER)) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL_MS, LOCATION_MIN_DISTANCE_M, this ) Log.d(TAG, "Registered for Network updates") } if (!providers.contains(LocationManager.GPS_PROVIDER) && !providers.contains(LocationManager.NETWORK_PROVIDER)) { Log.e(TAG, "No location providers available!") } } private fun stopLocationUpdates() { locationManager.removeUpdates(this) Log.d(TAG, "Location updates stopped") } } ``` ### MainActivity.kt ``` package dev.azom.privacypin import android.Manifest import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat class MainActivity : AppCompatActivity() { companion object { private const val TAG = "PrivacyPin" } private lateinit var toggleButton: Button private lateinit var statusText: TextView private lateinit var locationText: TextView private var isServiceRunning = false private val locationReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val lat = intent?.getDoubleExtra(LocationService.EXTRA_LATITUDE, 0.0) ?: return val lon = intent.getDoubleExtra(LocationService.EXTRA_LONGITUDE, 0.0) locationText.text = "Lat: $lat\nLon: $lon" } } private val foregroundLocationLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { permissions -> val fineGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true val coarseGranted = permissions[Manifest.permission.ACCESS_COARSE_LOCATION] == true if (fineGranted || coarseGranted) { Log.d(TAG, "Foreground location granted. Now requesting background...") requestBackgroundLocation() } else { Log.w(TAG, "Foreground location denied") Toast.makeText(this, "Location permission is required", Toast.LENGTH_LONG).show() } } private val backgroundLocationLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { granted -> if (granted) { Log.d(TAG, "Background location granted") requestNotificationPermissionOrStart() } else { Log.w(TAG, "Background location denied") Toast.makeText(this, "Background location is required for continuous tracking", Toast.LENGTH_LONG).show() } } private val notificationLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { granted -> if (granted) { Log.d(TAG, "Notification permission granted") } else { Log.w(TAG, "Notification permission denied (service will still work but notification may not show)") } startLocationService() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) toggleButton = findViewById(R.id.toggleButton) statusText = findViewById(R.id.statusText) locationText = findViewById(R.id.locationText) toggleButton.setOnClickListener { if (isServiceRunning) { stopLocationService() } else { checkPermissionsAndStart() } } updateUI() } override fun onResume() { super.onResume() val filter = IntentFilter(LocationService.ACTION_LOCATION_UPDATE) if (Build.VERSION.SDK_INT >= 33) { registerReceiver(locationReceiver, filter, Context.RECEIVER_NOT_EXPORTED) } else { registerReceiver(locationReceiver, filter) } } override fun onPause() { super.onPause() unregisterReceiver(locationReceiver) } private fun checkPermissionsAndStart() { if (hasForegroundLocationPermission()) { if (hasBackgroundLocationPermission()) { requestNotificationPermissionOrStart() } else { requestBackgroundLocation() } } else { requestForegroundLocation() } } private fun hasForegroundLocationPermission(): Boolean { return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED } private fun hasBackgroundLocationPermission(): Boolean { return if (Build.VERSION.SDK_INT >= 29) { ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED } else { true } } private fun hasNotificationPermission(): Boolean { return if (Build.VERSION.SDK_INT >= 33) { ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED } else { true } } private fun requestForegroundLocation() { foregroundLocationLauncher.launch( arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) ) } private fun requestBackgroundLocation() { if (Build.VERSION.SDK_INT >= 29) { backgroundLocationLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } else { requestNotificationPermissionOrStart() } } private fun requestNotificationPermissionOrStart() { if (Build.VERSION.SDK_INT >= 33 && !hasNotificationPermission()) { notificationLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) } else { startLocationService() } } private fun startLocationService() { Log.d(TAG, "Starting LocationService") val intent = Intent(this, LocationService::class.java) ContextCompat.startForegroundService(this, intent) isServiceRunning = true updateUI() } private fun stopLocationService() { Log.d(TAG, "Stopping LocationService") val intent = Intent(this, LocationService::class.java) stopService(intent) isServiceRunning = false locationText.text = "—" updateUI() } private fun updateUI() { if (isServiceRunning) { toggleButton.text = "Stop Sharing" statusText.text = "Status: ACTIVE" } else { toggleButton.text = "Start Sharing" statusText.text = "Status: Stopped" } } } ``` ### BootReceiver.kt ``` package dev.azom.privacypin import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import androidx.core.content.ContextCompat class BootReceiver : BroadcastReceiver() { companion object { private const val TAG = "PrivacyPin" } override fun onReceive(context: Context, intent: Intent) { if (intent.action == Intent.ACTION_BOOT_COMPLETED) { Log.d(TAG, "Boot completed received") val prefs = context.getSharedPreferences("privacypin_prefs", Context.MODE_PRIVATE) val wasRunning = prefs.getBoolean("service_running", false) if (wasRunning) { Log.d(TAG, "Service was running before reboot — restarting") val serviceIntent = Intent(context, LocationService::class.java) ContextCompat.startForegroundService(context, serviceIntent) } else { Log.d(TAG, "Service was NOT running before reboot — skipping") } } } } ``` ### test_server.py ``` #!/usr/bin/env python3 """ Simple HTTP test server for PrivacyPin. Listens on port 8080 and logs incoming location POSTs. Usage: python3 tools/test_server.py """ import json import sys from datetime import datetime from http.server import BaseHTTPRequestHandler, HTTPServer class LocationHandler(BaseHTTPRequestHandler): def do_POST(self): if self.path == "/location": content_length = int(self.headers.get("Content-Length", 0)) body = self.rfile.read(content_length).decode("utf-8") try: data = json.loads(body) timestamp = datetime.fromtimestamp(data.get("timestamp", 0) / 1000.0) print(f"\n{'=' * 50}") print(f" 📍 Location received at {datetime.now().strftime('%H:%M:%S')}") print(f" Lat: {data.get('lat')}") print(f" Lon: {data.get('lon')}") print(f" Accuracy: {data.get('accuracy')}m") print(f" Device time: {timestamp.strftime('%Y-%m-%d %H:%M:%S')}") print(f"{'=' * 50}") except json.JSONDecodeError: print(f"\n ⚠️ Invalid JSON received: {body}") self.send_response(200) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(b'{"status":"ok"}') else: self.send_response(404) self.end_headers() self.wfile.write(b"Not found") def log_message(self, format, *args): pass def main(): port = 8080 server = HTTPServer(("0.0.0.0", port), LocationHandler) print(f"🚀 PrivacyPin test server running on http://0.0.0.0:{port}") print(f" Waiting for location updates on POST /location ...") print(f" Press Ctrl+C to stop.\n") try: server.serve_forever() except KeyboardInterrupt: print("\n\nServer stopped.") server.server_close() if __name__ == "__main__": main() ``` --- ## How to Test (step by step) ``` # 1. Source environment source android_env.sh # 2. Start emulator sh tools/emulator_start.sh # 3. Build and deploy sh tools/build_and_deploy.sh # 4. Grant all permissions (skip UI dialogs) sh tools/grant_permissions.sh # 5. Start test server sh tools/start_test_server.sh # 6. Tap "Start Sharing" button on device adb shell input tap 540 1200 # 7. Send mock GPS location sh tools/mock_location.sh 45.5017 -73.5673 # 8. Check service is running sh tools/check_service.sh # 9. Check server received location cat /tmp/pp_server.log # 10. Check app logs adb logcat -d -v time -s PrivacyPin:V | tail -10 ``` --- ## Important Notes for Future Work 1. **`android:usesCleartextTraffic="true"`** is set for testing with HTTP. Remove this and use HTTPS for production. 2. **`SERVER_URL`** is hardcoded as `http://10.0.2.2:8080/location`. On a real device, change this to the actual server address. Make it configurable. 3. **The emulator's `10.0.2.2`** maps to the host machine's `localhost`. This only works in the Android emulator. 4. **GrapheneOS warning:** The `BOOT_COMPLETED` receiver was tested on stock AOSP emulator. GrapheneOS follows AOSP behavior here, but test on actual hardware to be sure. 5. **Battery optimization:** On real devices, some manufacturers aggressively kill services. GrapheneOS follows stock AOSP behavior (doesn't do this), but users may need to disable battery optimization for the app manually on other ROMs. 6. **The `START_STICKY` + `BOOT_COMPLETED` combination** gives maximum resilience. The only ways to stop the service are: user explicitly stopping it, user force-stopping from Settings, or user revoking permissions. 7. **Location interval:** Currently 60 seconds / 0 meters minimum distance. Adjust `LOCATION_INTERVAL_MS` in LocationService.kt. 8. **No retry queue:** If a server POST fails, the location is lost. For production, implement a local queue (Room DB or file) that retries failed uploads. 9. **Thread safety:** The `sendToServer` spawns a new thread per location update. For production, use a single-threaded executor or coroutines to avoid unbounded thread creation. 10. **The `Foreground service started from background can not have location access` warning** appears in logcat after boot. It's benign — the BOOT_COMPLETED exemption window grants access anyway. Location updates work fine.