Benutzer-Werkzeuge

Webseiten-Werkzeuge


location-app

Dies ist eine alte Version des Dokuments!


Here's a complete, minimal app that does this. It uses a foreground service (so logging continues while the screen is off or the app is backgrounded) and Google Play Services' FusedLocationProviderClient to get one location fix per minute, appending each fix as a CSV line.

app/src/main/
├── AndroidManifest.xml
├── java/com/example/locationlogger/
│   ├── MainActivity.kt
│   └── LocationLogService.kt
└── res/layout/activity_main.xml

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <!-- Required on Android 14+ for a location foreground service -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION"/>
    <!-- Android 13+: the persistent "logging" notification needs this -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
 
    <application
        android:allowBackup="true"
        android:label="Location Logger"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
 
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
 
        <service
            android:name=".LocationLogService"
            android:exported="false"
            android:foregroundServiceType="location"/>
    </application>
</manifest>

app/build.gradle.kts (relevant parts)

android {
    namespace = "com.example.locationlogger"
    compileSdk = 34
    defaultConfig {
        applicationId = "com.example.locationlogger"
        minSdk = 26          // notification channels + java.time available
        targetSdk = 34
    }
}
 
dependencies {
    implementation("androidx.core:core-ktx:1.13.1")
    implementation("androidx.appcompat:appcompat:1.7.0")
    implementation("com.google.android.gms:play-services-location:21.3.0")
}

MainActivity.kt

package com.example.locationlogger
 
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
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() {
 
    private lateinit var startButton: Button
    private lateinit var stopButton: Button
    private lateinit var statusText: TextView
 
    // Location permission — requested at runtime, as required since Android 6
    private val locationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { grants ->
        if (grants.values.any { it }) maybeRequestNotificationPermission()
        else toast("Location permission is required to log coordinates.")
    }
 
    // Notification permission (Android 13+) — needed for the foreground-service notification
    private val notificationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { granted ->
        if (granted) startLogging()
        else toast("Notification permission is required for the logging service.")
    }
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        startButton = findViewById(R.id.start_button)
        stopButton = findViewById(R.id.stop_button)
        statusText = findViewById(R.id.status_text)
 
        startButton.setOnClickListener { requestLocationPermissions() }
        stopButton.setOnClickListener {
            ContextCompat.startForegroundService(
                this,
                Intent(this, LocationLogService::class.java).apply { action = LocationLogService.ACTION_STOP }
            )
            statusText.text = "Stopping…"
        }
    }
 
    override fun onResume() {
        super.onResume()
        if (LocationLogService.isRunning) {
            statusText.text = "Logging every minute →\n${LocationLogService.logFile(this)}"
        } else {
            statusText.text = "Not logging"
        }
    }
 
    private fun requestLocationPermissions() {
        val perms = arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
        if (perms.any { ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED }) {
            locationPermissionLauncher.launch(perms)
        } else {
            maybeRequestNotificationPermission()
        }
    }
 
    private fun maybeRequestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
            ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
        ) {
            notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
        } else {
            startLogging()
        }
    }
 
    private fun startLogging() {
        ContextCompat.startForegroundService(
            this,
            Intent(this, LocationLogService::class.java).apply { action = LocationLogService.ACTION_START }
        )
        statusText.text = "Logging every minute →\n${LocationLogService.logFile(this)}"
    }
 
    private fun toast(msg: String) = Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}

LocationLogService.kt

package com.example.locationlogger
 
import android.Manifest
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.content.pm.PackageManager
import android.os.IBinder
import android.os.Looper
import androidx.core.app.NotificationCompat
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import java.io.File
import java.time.Instant
 
class LocationLogService : Service() {
 
    private val fusedClient = LocationServices.getFusedLocationProviderClient(this)
    private var logFile: File? = null
 
    // One fix arrives roughly every 60 s; append it as a CSV line.
    private val locationCallback = LocationCallback { result ->
        val loc = result.lastLocation ?: return@LocationCallback
        val line = "${Instant.ofEpochMilli(loc.time)},${loc.latitude},${loc.longitude},${loc.accuracy}\n"
        // One tiny write per minute — cheap enough to do inline.
        logFile?.appendText(line)
    }
 
    override fun onBind(intent: Intent?): IBinder? = null
 
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            ACTION_START -> startLogging()
            ACTION_STOP -> stopLogging()
            null -> startLogging() // process was killed and restarted by the system; resume logging
        }
        return START_STICKY
    }
 
    private fun startLogging() {
        // 1. Become a foreground service so the OS doesn't kill us while logging.
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, buildNotification("Logging location every minute"))
 
        // 2. Open (or create) the log file; add a header if it's new.
        val file = logFile(this)
        if (!file.exists()) {
            file.parentFile?.mkdirs()
            file.appendText("timestamp_utc,latitude,longitude,accuracy_m\n")
        }
        logFile = file
 
        // 3. Ask for one location update per minute.
        val request = LocationRequest.Builder(LocationRequest.PRIORITY_HIGH_ACCURACY, 60_000L)
            .setFastestIntervalMillis(60_000L)
            .build()
 
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
            checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
        ) {
            fusedClient.requestLocationUpdates(request, locationCallback, Looper.getMainLooper())
            isRunning = true
        } else {
            stopSelf() // shouldn't happen — the activity checks first
        }
    }
 
    private fun stopLogging() {
        fusedClient.removeLocationUpdates(locationCallback)
        isRunning = false
        stopForeground(STOP_FOREGROUND_REMOVE)
        stopSelf()
    }
 
    private fun buildNotification(text: String): Notification {
        val stopIntent = Intent(this, LocationLogService::class.java).apply { action = ACTION_STOP }
        val stopPending = PendingIntent.getService(
            this, 0, stopIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Location Logger")
            .setContentText(text)
            .setSmallIcon(android.R.drawable.ic_menu_mylocation)
            .setOngoing(true)
            .addAction(0, "Stop", stopPending) // user can stop from the notification
            .build()
    }
 
    private fun createNotificationChannel() {
        val channel = NotificationChannel(CHANNEL_ID, "Logging status", NotificationManager.IMPORTANCE_LOW)
        getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
    }
 
    companion object {
        private const val CHANNEL_ID = "location_logger"
        private const val NOTIFICATION_ID = 1
        const val ACTION_START = "com.example.locationlogger.START"
        const val ACTION_STOP = "com.example.locationlogger.STOP"
 
        @Volatile
        var isRunning = false
            private set
 
        // App-specific external dir: no storage permission needed, and visible in file managers.
        fun logFile(context: Context): File =
            File(context.getExternalFilesDir(null), "location_log.csv")
    }
}

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="24dp">
 
    <TextView
        android:id="@+id/status_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:gravity="center"/>
 
    <Button
        android:id="@+id/start_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Start logging"/>
 
    <Button
        android:id="@+id/stop_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop logging"/>
</LinearLayout>

Notes

  • Where the log goes: Android/data/com.example.locationlogger/files/location_log.csv on internal storage. No storage permission is needed for this location, and it's visible in file managers / retrievable via adb pull. Each line: 2024-05-01T12:34:56.789Z,48.85837,2.29448,5.0
  • Permissions flow: tapping Start triggers the runtime location dialog (and on Android 13+, the notification dialog) before launching the service — exactly what you asked for.
  • „Every minute“ caveat: FusedLocationProviderClient delivers updates at roughly the requested rate, but the system may coalesce or delay them slightly (especially in Doze). For a quick test, change both intervals to 5_000L. If you need strictly one line per 60 s regardless of GPS callbacks, keep a cached last location and write it from a Handler/coroutine timer tick instead.
  • Battery optimization: for long unattended logging, exempt the app so Doze doesn't throttle updates:
val pm = getSystemService(PowerManager::class.java)
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
    startActivity(Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
        Uri.parse("package:$packageName")))
}
  • Android 14+ requirement: the FOREGROUND_SERVICE_LOCATION permission and foregroundServiceType="location" in the manifest are mandatory for a location foreground service — both are included above.
location-app.1794329031.txt.gz · Zuletzt geändert: von martin