我正在尝试使用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()
}
你应该像这样将上下文参数传递给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")
}
}
}
我建议你不要使用LocalBroadcastManager,因为它在android O和Later的android版本中没用。
你可以在这里阅读Implicit-broadcast-exceptions
我会建议使用EventBus,因为它是在应用程序内任何地方传输数据的最佳解决方案 - 不使用上下文对象,也适用于所有Android版本。