PeriodicWorkRequest 仅在 android 中调用一次

PeriodicWorkRequest calls single time only in android

我正在开发我正在使用的后台定位服务 PeriodicWorker。为此,我设置了 1 分钟的间隔。我希望我的服务每 1 分钟触发一次,但目前它只调用一次。 我想要的是每 1 分钟调用一次此服务,下面给出了我的代码,请指导我解决这个问题。

谢谢

我从 MainActivty

onCreate 方法调用的这段代码
val periodicWork =
        PeriodicWorkRequest.Builder(MyWorker::class.java, 1, TimeUnit.MINUTES)
            .addTag("Track24Tag")
            .build()
    WorkManager.getInstance()
        .enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.REPLACE, periodicWork)

这是我的WorkerClass

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
    }

}

定期工作请求的最小间隔为 15 分钟。