如何在另一个类中添加Context类?

问题描述 投票:0回答:3

我正在尝试使用Localbroadcast将经度和经度发送到主要活动。但是thisgetInstance()的参数不起作用。我尝试添加上下文类但它仍然是错误的。有任何想法吗?谢谢。

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()
        }
android kotlin
3个回答
0
投票

尝试

 this@LocationTrackingService

得到LocationTrackingServicethis对象。

更多关于this对象here


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")
        }
    }
}

-1
投票

我建议你不要使用LocalBroadcastManager,因为它在android O和Later的android版本中没用。

你可以在这里阅读Implicit-broadcast-exceptions

我会建议使用EventBus,因为它是在应用程序内任何地方传输数据的最佳解决方案 - 不使用上下文对象,也适用于所有Android版本。

© www.soinside.com 2019 - 2024. All rights reserved.