Skip to main content
Glama

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
NameRequiredDescriptionDefault
locationAccuracyYesLocation accuracy requirements
permissionsNo
geofencingNo
coordinateCaptureNo
offlineMappingNoInclude offline map support

Implementation Reference

  • 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)
    }
    \`\`\`
    `;
    }
  • 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,
          },
        ],
      };
  • 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'],
  • 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
        }
    }
    \`\`\``;
    }
  • 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
            }
        }
    }
    \`\`\``;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. While 'configure' implies a write operation, it doesn't specify whether this requires specific permissions, whether changes are reversible, what happens to existing settings, or any rate limits. The description lacks crucial behavioral context for a configuration tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It's appropriately sized and front-loaded with the essential information, making it easy to understand at a glance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a configuration tool with 5 parameters (including nested objects), no annotations, no output schema, and only 40% schema description coverage, the description is insufficient. It doesn't address what the tool returns, error conditions, or the scope of configuration changes, leaving significant gaps for an agent to understand the tool's full behavior.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is only 40%, meaning most parameters lack documentation in the schema. The description provides no additional parameter information beyond the tool name's implication of location services. It doesn't explain what the five parameters control, their relationships, or practical usage examples to compensate for the low schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('configure') and target ('GPS and location services for DHIS2 Android app'), providing a specific verb+resource combination. However, it doesn't explicitly differentiate from sibling tools like 'dhis2_android_configure_camera' or 'dhis2_android_configure_notifications', which also configure specific Android app features.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. There are no mentions of prerequisites, timing considerations, or comparisons to sibling tools that handle related configurations like 'dhis2_android_configure_notifications' or 'dhis2_android_setup_sync'.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Dradebo/dhis2-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server