androidandroid-workmanagerlocation-services

PeriodicWorkRequest calls single time only in android


I am working on background location service for which I am using PeriodicWorker. For this I am setting 1 Minute interval. I want my service to trigger after every 1 minute, but currently it is calling one time only. What I want is to call this service after every 1 minute, my code is given below kindly guide me to solve this issue.

Thanks

This code I am calling from onCreate method of my MainActivty

val periodicWork =
        PeriodicWorkRequest.Builder(MyWorker::class.java, 1, TimeUnit.MINUTES)
            .addTag("Track24Tag")
            .build()
    WorkManager.getInstance()
        .enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.REPLACE, periodicWork)

This is my Worker Class

class MyWorker(private val mContext: Context, workerParams: WorkerParameters) :
    Worker(mContext, workerParams) {
    /**
     * The current location.
     */
    private var mLocation: Location? = null

    /**
     * Provides access to the Fused Location Provider API.
     */
    private var mFusedLocationClient: FusedLocationProviderClient? =
        LocationServices.getFusedLocationProviderClient(mContext)

    /**
     * Callback for changes in location.
     */
    private var mLocationCallback: LocationCallback? = null
    override fun doWork(): Result {

        try {
            mLocationCallback = object : LocationCallback() {
                override fun onLocationResult(locationResult: LocationResult) {
                    super.onLocationResult(locationResult)
                }
            }
            val mLocationRequest = LocationRequest()
            mLocationRequest.interval = UPDATE_INTERVAL_IN_MILLISECONDS
            mLocationRequest.fastestInterval = FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS
            mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
            try {
                mFusedLocationClient!!.lastLocation.addOnCompleteListener { task ->
                    if (task.isSuccessful && task.result != null) {
                        mLocation = task.result
                        Log.d(
                            TAG,
                            "Location : $mLocation"
                        )

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            val name: CharSequence = "Track24"
                            val description = "Track24"
                            val importance = NotificationManager.IMPORTANCE_DEFAULT
                            val channel = NotificationChannel(
                                "Track24", name, importance
                            )
                            channel.description = description

                            val notificationManager = mContext.getSystemService(
                                NotificationManager::class.java
                            )
                            notificationManager.createNotificationChannel(channel)
                        }
                        val builder =
                            NotificationCompat.Builder(mContext, "Track24")
                                .setSmallIcon(android.R.drawable.ic_menu_mylocation)
                                .setContentTitle("New Location Update")
                                .setContentText(
                                    "You are at " + getCompleteAddressString(
                                        mLocation!!.latitude,
                                        mLocation!!.longitude
                                    )
                                ).setPriority(NotificationCompat.PRIORITY_DEFAULT)
                                .setStyle(
                                    NotificationCompat.BigTextStyle().bigText(
                                        "You are at " + getCompleteAddressString(
                                            mLocation!!.latitude,
                                            mLocation!!.longitude
                                        )
                                    )
                                )
                        val notificationManager =
                            NotificationManagerCompat.from(mContext)

                        // notificationId is a unique int for each notification that you must define
                        notificationManager.notify(1001, builder.build())
                        mFusedLocationClient!!.removeLocationUpdates(mLocationCallback)
                    } else {
                        Log.w(
                            TAG,
                            "Failed to get location."
                        )
                    }
                }
            } catch (unlikely: SecurityException) {
                Log.e(
                    TAG,
                    "Lost location permission.$unlikely"
                )
            }
            try {
                mFusedLocationClient!!.requestLocationUpdates(mLocationRequest, null)
            } catch (unlikely: SecurityException) {
                Log.e(
                    TAG,
                    "Lost location permission. Could not request updates. $unlikely"
                )
            }
        } catch (ignored: ParseException) {
            Log.e("Exception: ", ignored.message)
        }
        return Result.success()
    }

    private fun getCompleteAddressString(
        LATITUDE: Double,
        LONGITUDE: Double
    ): String {
        var strAdd = ""
        val geocoder = Geocoder(mContext, Locale.getDefault())
        try {
            val addresses =
                geocoder.getFromLocation(LATITUDE, LONGITUDE, 1)
            if (addresses != null) {
                val returnedAddress = addresses[0]
                val strReturnedAddress = StringBuilder()
                for (i in 0..returnedAddress.maxAddressLineIndex) {
                    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n")
                }
                strAdd = strReturnedAddress.toString()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return strAdd
    }

    companion object {
        private const val TAG = "MyWorker"

        /**
         * The desired interval for location updates. Inexact. Updates may be more or less frequent.
         */
        private const val UPDATE_INTERVAL_IN_MILLISECONDS: Long = 2000

        /**
         * The fastest rate for active location updates. Updates will never be more frequent
         * than this value.
         */
        private const val FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            UPDATE_INTERVAL_IN_MILLISECONDS / 2
    }

}

Solution

  • Periodic work requests have a minimum interval of 15 minutes.

    enter image description here