Android Kotlin Project – Vehicle Tracking App

FREE Online Courses: Elevate Your Skills, Zero Cost Attached - Enroll Now!

Hello there, Android enthusiasts! Today, we will look at and learn how to develop an Android Kotlin project, which is a Vehicle Tracking application in Android Studio. In this android kotlin vehicle tracking app, we’ll learn about the entire project’s development.

The Android app “Vehicle Tracking” uses a notification to track the location of a smartphone inside a car, providing the longitude, latitude, and accuracy of the location. When travelling to an unfamiliar area, it is useful for the user to be aware of their specific location. Using the coordinates, they can do this.

About Android Kotlin Vehicle Tracking Application

This is a simple project for those just learning the fundamentals of developing Android applications. This Android app’s user interface is quite basic and contains only two buttons, i.e. ‘Start’ and ‘Stop’.

Details about the user interface are as follows:

1. The user is prompted to allow location access when the app is first launched so that it can keep track of the device’s current position.
2. The user interface consists of a text view that displays the daily step goal set by the user.
3. The user interface of the application contains two buttons, ‘Start’ and ‘Stop’, respectively.
4. When the ‘Start’ button is clicked, the coordinates and the accuracy are shown to the user through a notification.
5. Only when the ‘Stop’ button is clicked the application will stop fetching the exact location of the device.

Prerequisites for Vehicle Tracking App Using Android Kotlin

To develop this Vehicle Tracking Android application, the requirements and prerequisites are as follows:

1. Kotlin: You must become acquainted with Kotlin programming first. It is necessary because we’ll be writing the app’s code in the programming language Kotlin.
2. Android Studio: Android Studio is at the core of our application because it is how we will create it. An Android virtual device that can be used to test an application’s functionality is also available with Android Studio.

Download Android Kotlin Vehicle Tracking App Project

Please download the source code of Android Kotlin Vehicle Tracking Project: Android Kotlin Vehicle Tracking App Project Code.

Develop a Vehicle Tracking application in Android Studio.

We’ll now start working on developing an Android Kotlin Vehicle Tracking application. Before actually implementing and executing the code, we will learn about its working. So, let’s look at the files and functions needed to run the code:

In order to make this Android Kotlin Vehicle Tracking application, you must follow a set of instructions.

1. To the location of your choice, extract all the files from the downloaded zip file.
2. Launch Android Studio.
3. Open by selecting File.
4. Locate and choose the extracted folder, then select OK.

The Android Kotlin Vehicle Tracking application’s source code has been successfully opened in Android Studio.

Vehicle Tracking application’s source

1. ‘LocationClient.kt’ is an interface which is responsible for getting the updated location of the device at specified intervals.

Code:

interface LocationClient {
    fun getLocationUpdates(interval: Long): Flow<Location>

    class LocationException(message: String): Exception()
}

2. ‘contextExt.kt’ is a kotlin that checks whether the required permissions to fetch location details are granted by the user or not.

The function hasLocationPermission() checks if the app has been granted permission to access the user’s location. The function takes a Context object as input and returns a Boolean value. If the app has been granted permission, the function returns true. Otherwise, the function returns false.

The function works by calling the checkSelfPermission() method on the ContextCompat object. The checkSelfPermission() method takes two parameters: the Context object and the name of the permission that you want to check. The function then checks if the permission has been granted and returns the appropriate value.

fun Context.hasLocationPermission(): Boolean {
    return ContextCompat.checkSelfPermission(
        this,
        Manifest.permission.ACCESS_COARSE_LOCATION
    ) == PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
}

3. ‘defaultLocationClient.kt’ is a kotlin file that checks whether the GPS and internet are enabled on the device, which will assist in providing the location and also request for the location at specified intervals.

  • The ‘DefaultLocationClient’ class is a class that provides a way to get location updates from the user’s device.
  • The class takes a Context object and a ‘FusedLocationProviderClient’ object as input.
  • The Context object is used to get the user’s location permission and to check if GPS is enabled. The‘FusedLocationProviderClient’ object is used to request location updates from the user’s device.
  • The DefaultLocationClient class has a method called ‘getLocationUpdates’.
  • The ‘getLocationUpdates’ method takes a Long value as input and returns a Flow of Location objects.
  • The Long value specifies the interval at which location updates are requested.
  • The Flow of Location objects emits the user’s location whenever a new location update is received.
class DefaultLocationClient(
    private val context: Context,
    private val client: FusedLocationProviderClient
): LocationClient {

    @SuppressLint("MissingPermission")
    override fun getLocationUpdates(interval: Long): Flow<Location> {
        return callbackFlow {
            if(!context.hasLocationPermission()) {
                throw LocationClient.LocationException("Missing location permission")
            }

            val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
            val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            val isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
            if(!isGpsEnabled && !isNetworkEnabled) {
                throw LocationClient.LocationException("GPS is disabled")
            }

            val request = LocationRequest.create()
                .setInterval(interval)
                .setFastestInterval(interval)

            val locationCallback = object : LocationCallback() {
                override fun onLocationResult(result: LocationResult) {
                    super.onLocationResult(result)
                    result.locations.lastOrNull()?.let { location ->
                        launch { send(location) }
                    }
                }
            }

            client.requestLocationUpdates(
                request,
                locationCallback,
                Looper.getMainLooper()
            )

            awaitClose {
                client.removeLocationUpdates(locationCallback)
            }
        }
    }
}

4. ‘LocationService.kt’ is a file that is responsible for fetching and displaying the location in the foreground.

The LocationService class is a service that tracks the user’s location. The service uses the DefaultLocationClient class to get location updates from the user’s device. The service then displays the user’s location in a notification.

The LocationService class has the following methods:

  • When the service is formed, the onCreate() method is called. The method creates a DefaultLocationClient object and starts getting location updates.
  • This function is invoked when the service is started (onStartCommand()).
  • The method checks the intent that was used to start the service and starts or stops the location tracking.
  • start(): This method starts the location tracking. The method creates a notification and starts getting location updates.
  • stop(): This method stops the location tracking. The method removes the notification and stops getting location updates.
  • When the service is terminated, the method onDestroy() is invoked. The technique clears the resources and cancels the location updates.

The LocationService class has the following companion object:

ACTION_START: This constant is used to start the location tracking.
ACTION_STOP: This constant is used to stop the location tracking.

class LocationService: Service() {

    private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    private lateinit var locationClient: LocationClient

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        locationClient = DefaultLocationClient(
            applicationContext,
            LocationServices.getFusedLocationProviderClient(applicationContext)
        )
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when(intent?.action) {
            ACTION_START -> start()
            ACTION_STOP -> stop()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    private fun start() {
        val notification = NotificationCompat.Builder(this, "location")
            .setContentTitle("Tracking location...")
            .setContentText("Location: null")
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setOngoing(true)

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        locationClient
            .getLocationUpdates(10000L)
            .catch { e -> e.printStackTrace() }
            .onEach { location ->
                val lat = location.latitude.toString()
                val long = location.longitude.toString()
                val acc = location.accuracy.toString()
                val updatedNotification = notification.setContentText(
                    "Location: (Latitude: $lat, Longitude:$long, Accuracy: $acc m)"
                )
                notificationManager.notify(1, updatedNotification.build())
            }
            .launchIn(serviceScope)

        startForeground(1, notification.build())
    }

    private fun stop() {
        stopForeground(true)
        stopSelf()
    }

    override fun onDestroy() {
        super.onDestroy()
        serviceScope.cancel()
    }

    companion object {
        const val ACTION_START = "ACTION_START"
        const val ACTION_STOP = "ACTION_STOP"
    }
}

5. ‘LocationApp.kt’ is a file that defines the notification channel; it is an integral file, and without this, the notification function won’t work.

The LocationApp class has the following methods:

onCreate(): This method is called when the application is created. The method creates a notification channel if the device is running Android 8.0 or higher.

The LocationApp class can be used to track the user’s location in an application. The application can use the notification channel to display notifications about location tracking.

class LocationApp: Application() {

        override fun onCreate() {
        super.onCreate()
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(
        "location",
        "Location",
        NotificationManager.IMPORTANCE_LOW
        )
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
        }
        }
}

6. The user interface of the application and the functionality of the two buttons on the home screen are created by the kotlin file ‘MainActivity.kt’.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
            ),
            0
        )
        setContent {
            VehicleTrackingProjectGurukulTheme {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(text = "Vehicle Tracking Application - ProjectGurukul", fontSize = 20.sp)
                    Button(onClick = {
                        Intent(applicationContext, LocationService::class.java).apply {
                            action = LocationService.ACTION_START
                            startService(this)
                        }
                    }) {
                        Text(text = "Start")
                    }
                    Spacer(modifier = Modifier.height(16.dp))
                    Button(onClick = {
                        Intent(applicationContext, LocationService::class.java).apply {
                            action = LocationService.ACTION_STOP
                            startService(this)
                        }
                    }) {
                        Text(text = "Stop")
                    }
                }
            }
        }
    }
}}

Android Kotlin Vehicle Tracking App Output:

1. Asking for permission (Select ‘While using the app’ for the application to work)

 

android kotlin asking permission

 

2. Home Screen

android kotlin home screen

 

3. Tracking Location (For demonstration purposes, just the last five digits of the latitude and longitude are shown; however, the source code contains code that will fetch and display the correct coordinates.)

android kotlin tracking location

 

Summary

So, in this android kotlin vehicle tracking app, we learned how to utilise Android Studio to create an application that retrieves the device’s real-time location to aid with location monitoring. This android kotlin project is suitable for beginners as it will improve your ability to design user interfaces as per the application’s need without the need to know XML, using only Kotlin and adding functionality using some extra permissions from the user. We sincerely hope you enjoyed it, and we have no doubt that you will enjoy applying it.

If you are Happy with ProjectGurukul, do not forget to make us happy with your positive feedback on Google | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *