dhis2_android_setup_location_services
Configure GPS and location services for the DHIS2 Android app to enable accurate data collection with geofencing and offline mapping capabilities.
Instructions
Configure GPS and location services for DHIS2 Android app
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| locationAccuracy | Yes | Location accuracy requirements | |
| permissions | No | ||
| geofencing | No | ||
| coordinateCapture | No | ||
| offlineMapping | No | Include offline map support |
Implementation Reference
- src/android-generators.ts:842-934 (handler)Main handler function that generates complete Android location services configuration including permissions, LocationManager, geofencing, offline mapping, usage examples, and tests based on input parameters.export function generateLocationServicesConfig(args: any): string { const { locationAccuracy, permissions, geofencing, coordinateCapture, offlineMapping } = args; return `# DHIS2 Android Location Services Configuration ## Location Accuracy: ${locationAccuracy.toUpperCase()} ${generateLocationServiceImplementation(locationAccuracy, permissions, geofencing, coordinateCapture, offlineMapping)} ## AndroidManifest.xml Permissions \`\`\`xml ${permissions.fineLocation ? '<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />' : ''} ${permissions.coarseLocation ? '<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />' : ''} ${permissions.backgroundLocation ? '<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />' : ''} ${offlineMapping ? '<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />' : ''} <!-- Location hardware features --> <uses-feature android:name="android.hardware.location" android:required="false" /> <uses-feature android:name="android.hardware.location.gps" android:required="false" /> \`\`\` ## Implementation ${generateLocationManagerCode(locationAccuracy, geofencing, coordinateCapture, permissions)} ${geofencing.enabled ? generateGeofencingCode(geofencing) : ''} ${offlineMapping ? generateOfflineMappingCode() : ''} ## Usage Examples \`\`\`kotlin class DataEntryActivity : AppCompatActivity() { @Inject lateinit var locationManager: DHIS2LocationManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Request location permissions locationManager.requestPermissions(this) // Capture coordinates for data entry binding.captureLocationButton.setOnClickListener { captureCurrentLocation() } } private fun captureCurrentLocation() { lifecycleScope.launch { try { val location = locationManager.getCurrentLocation() // Update data element with coordinates updateCoordinateDataElement(location) } catch (e: Exception) { showLocationError(e.message) } } } private fun updateCoordinateDataElement(location: Location) { val coordinates = "\${location.latitude},\${location.longitude}" // Update DHIS2 data value with coordinates d2.dataValueModule().dataValues() .value(dataElementId, orgUnitId, periodId, categoryOptionComboId) .set(coordinates) } } \`\`\` ## Testing Location Services \`\`\`kotlin @Test fun testLocationCapture() { // Mock location for testing val mockLocation = Location("test").apply { latitude = -1.2921 longitude = 36.8219 accuracy = 5.0f } val result = locationValidator.validateLocation(mockLocation) assertTrue(result.isValid) } \`\`\` `; }
- src/index.ts:1285-1295 (handler)MCP server dispatch handler that receives tool call parameters and invokes the location services generator function.case 'dhis2_android_setup_location_services': const locationArgs = args as any; const locationConfig = generateLocationServicesConfig(locationArgs); return { content: [ { type: 'text', text: locationConfig, }, ], };
- src/permission-system.ts:155-168 (registration)Permission registration mapping the tool to required user permission 'canUseMobileFeatures' for access control.['dhis2_android_init_project', 'canUseMobileFeatures'], ['dhis2_android_configure_gradle', 'canUseMobileFeatures'], ['dhis2_android_setup_sync', 'canConfigureMobile'], ['dhis2_android_configure_storage', 'canConfigureMobile'], ['dhis2_android_setup_location_services', 'canUseMobileFeatures'], ['dhis2_android_configure_camera', 'canUseMobileFeatures'], ['dhis2_android_setup_authentication', 'canConfigureMobile'], ['dhis2_android_generate_data_models', 'canUseMobileFeatures'], ['dhis2_android_setup_testing', 'canUseMobileFeatures'], ['dhis2_android_configure_ui_patterns', 'canUseMobileFeatures'], ['dhis2_android_setup_offline_analytics', 'canUseMobileFeatures'], ['dhis2_android_configure_notifications', 'canUseMobileFeatures'], ['dhis2_android_performance_optimization', 'canUseMobileFeatures'],
- src/android-generators.ts:958-1035 (helper)Helper function generating the core DHIS2LocationManager Kotlin class implementation with FusedLocationProviderClient integration.function generateLocationManagerCode(accuracy: string, geofencing: any, capture: any, permissions: any): string { return ` \`\`\`kotlin @Singleton class DHIS2LocationManager @Inject constructor( @ApplicationContext private val context: Context ) { private val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context) private val locationRequest = createLocationRequest() private fun createLocationRequest(): LocationRequest { return LocationRequest.Builder( Priority.${getLocationPriority(accuracy)}, ${capture.timeoutSeconds ? capture.timeoutSeconds * 1000 : 10000}L // ${capture.timeoutSeconds || 10} seconds ).apply { setWaitForAccurateLocation(${capture.validation || false}) ${capture.accuracyThreshold ? `setMinUpdateDistanceMeters(${capture.accuracyThreshold}f)` : ''} }.build() } suspend fun getCurrentLocation(): Location { return withContext(Dispatchers.IO) { suspendCancellableCoroutine { continuation -> if (!hasLocationPermission()) { continuation.resumeWithException(SecurityException("Location permission not granted")) return@suspendCancellableCoroutine } fusedLocationClient.getCurrentLocation( Priority.${getLocationPriority(accuracy)}, null ).addOnSuccessListener { location -> if (location != null) { ${capture.validation ? 'if (isLocationAccurate(location)) {' : ''} continuation.resume(location) ${capture.validation ? '} else { continuation.resumeWithException(Exception("Location accuracy insufficient")) }' : ''} } else { continuation.resumeWithException(Exception("Unable to get location")) } }.addOnFailureListener { exception -> continuation.resumeWithException(exception) } } } } ${capture.validation ? ` private fun isLocationAccurate(location: Location): Boolean { return location.accuracy <= ${capture.accuracyThreshold || 10}f }` : ''} fun hasLocationPermission(): Boolean { return ContextCompat.checkSelfPermission( context, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED } fun requestPermissions(activity: Activity) { val requestPermissions = mutableListOf<String>() ${permissions.fineLocation ? 'requestPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION)' : ''} ${permissions.coarseLocation ? 'requestPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION)' : ''} ${permissions.backgroundLocation ? 'requestPermissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)' : ''} ActivityCompat.requestPermissions( activity, requestPermissions.toTypedArray(), LOCATION_PERMISSION_REQUEST_CODE ) } companion object { private const val LOCATION_PERMISSION_REQUEST_CODE = 1001 } } \`\`\``; }
- src/android-generators.ts:1047-1127 (helper)Helper function generating geofencing support with GeofenceManager and BroadcastReceiver implementations.function generateGeofencingCode(geofencing: any): string { return ` ## Geofencing Implementation \`\`\`kotlin @Singleton class GeofenceManager @Inject constructor( @ApplicationContext private val context: Context ) { private val geofencingClient = LocationServices.getGeofencingClient(context) private val geofencePendingIntent by lazy { createGeofencePendingIntent() } fun addGeofence( id: String, latitude: Double, longitude: Double, radius: Float = ${geofencing.radius}f ) { val geofence = Geofence.Builder() .setRequestId(id) .setCircularRegion(latitude, longitude, radius) .setTransitionTypes(${geofencing.triggers.map((trigger: string) => getGeofenceTransition(trigger)).join(' or ')}) .setExpirationDuration(Geofence.NEVER_EXPIRE) .build() val geofenceRequest = GeofencingRequest.Builder() .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER) .addGeofence(geofence) .build() if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { geofencingClient.addGeofences(geofenceRequest, geofencePendingIntent) .addOnSuccessListener { Log.d("Geofence", "Added geofence: $id") } .addOnFailureListener { exception -> Log.e("Geofence", "Failed to add geofence: $id", exception) } } } private fun createGeofencePendingIntent(): PendingIntent { val intent = Intent(context, GeofenceBroadcastReceiver::class.java) return PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } } class GeofenceBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val geofencingEvent = GeofencingEvent.fromIntent(intent) if (geofencingEvent?.hasError() == true) { Log.e("Geofence", "Geofence error: \${geofencingEvent.errorCode}") return } val geofenceTransition = geofencingEvent?.geofenceTransition when (geofenceTransition) { ${geofencing.triggers.includes('enter') ? 'Geofence.GEOFENCE_TRANSITION_ENTER -> handleEnterEvent(geofencingEvent)' : ''} ${geofencing.triggers.includes('exit') ? 'Geofence.GEOFENCE_TRANSITION_EXIT -> handleExitEvent(geofencingEvent)' : ''} ${geofencing.triggers.includes('dwell') ? 'Geofence.GEOFENCE_TRANSITION_DWELL -> handleDwellEvent(geofencingEvent)' : ''} } } private fun handleEnterEvent(event: GeofencingEvent) { // Handle facility entry event.triggeringGeofences?.forEach { geofence -> Log.d("Geofence", "Entered geofence: \${geofence.requestId}") // Trigger data entry workflow } } } \`\`\``; }