我正在尝试使用Localbroadcast将经纬度发送到主要活动。但是this
中getInstance()
的参数不起作用。我尝试添加上下文类,但这仍然是错误的。有任何想法吗?谢谢。
companion object {
val TAG = "LocationTrackingService"
val INTERVAL = 5000.toLong() // In milliseconds
val DISTANCE = 0.toFloat() // In meters
val locationListeners = arrayOf(
LTRLocationListener(LocationManager.GPS_PROVIDER),
LTRLocationListener(LocationManager.NETWORK_PROVIDER)
)
private fun sendRequest() {
// The string "GPS_not_activaded" will be used to filer the intent
val intentRequest = Intent("Sending_location_coordinates")
LocalBroadcastManager.getInstance(this).sendBroadcast(intentRequest)
Log.d(TAG,"Se enviaron las coordenadas")
}
class LTRLocationListener(provider: String) : android.location.LocationListener {
val lastLocation = Location(provider)
override fun onLocationChanged(location: Location?) {
lastLocation.set(location)
Log.d(TAG, "======================= New Data =======================")
Log.d(TAG,"latitud: "+ lastLocation.latitude)
Log.d(TAG,"longitud: "+ lastLocation.longitude)
sendRequest()
}
答案 0 :(得分:0)
答案 1 :(得分:0)
您应像这样将上下文参数传递给sendRequest
方法。
class LocationTrackingService : Service(){
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// Pass this as context here
sendRequest(this)
return super.onStartCommand(intent, flags, startId)
}
companion object {
val TAG = "LocationTrackingService"
val INTERVAL = 5000.toLong() // In milliseconds
val DISTANCE = 0.toFloat() // In meters
val locationListeners = arrayOf(
LTRLocationListener(LocationManager.GPS_PROVIDER),
LTRLocationListener(LocationManager.NETWORK_PROVIDER)
)
private fun sendRequest(context: Context) {
// The string "GPS_not_activaded" will be used to filer the intent
val intentRequest = Intent("Sending_location_coordinates")
LocalBroadcastManager.getInstance(context).sendBroadcast(intentRequest)
Log.d(TAG, "Se enviaron las coordenadas")
}
}
}
答案 2 :(得分:-1)
我建议您不要使用 LocalBroadcastManager ,因为它在 android O 和以后 android版本中不会有帮助。
您可以在这里Implicit-broadcast-exceptions
阅读我建议使用EventBus,因为它是最佳解决方案,可传输应用内任意位置的数据-不使用上下文 >对象,并且还可以在所有android版本中使用。