android - PeriodicWorkRequest 仅在 android 中调用单次
问题描述
我正在使用我正在使用的后台定位服务PeriodicWorker
。为此,我设置了 1 分钟间隔。我希望我的服务每 1 分钟触发一次,但目前它只调用一次。我想要的是每 1 分钟调用一次该服务,下面给出了我的代码,请指导我解决这个问题。
谢谢
我从onCreate
MainActivty 的方法调用的这段代码
val periodicWork =
PeriodicWorkRequest.Builder(MyWorker::class.java, 1, TimeUnit.MINUTES)
.addTag("Track24Tag")
.build()
WorkManager.getInstance()
.enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.REPLACE, periodicWork)
这是我的Worker
课
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
}
}
解决方案
推荐阅读
- spring - 带有 Jboss eap 6.4 的 Spring Boot 2.0.1
- swift - 无法修复我的 playAudio 函数 - 错误参数标签 '(contentsOf:, error:)' 与任何可用的重载都不匹配
- java - Android 和 ASP.net Core Application (C#) 中 GET/POST 请求的签名生成和验证
- typescript - typescript 的 document.getElementbyID 有什么问题?
- c# - HTTPListener 未在 .NET 4.6 和 Server2012R2 上使用 TLS 1.1 / 1.2
- typescript - 在 typescript 中使用“true”作为类型
- java - Android 在活动开始时询问相机权限
- revit-api - 编辑元素几何体(修剪连接的元素)
- angular - 使用从角度服务返回的结果时出错(未定义)
- oracle11g - ORA-02396: 超过了 node-oracledb 的最大空闲时间