Как настроить обратный звонок от сервиса к активности в Котлине? - PullRequest
1 голос
/ 30 октября 2019

Я новичок в Котлине и пытаюсь передать данные о местоположении из моего сервиса в мою деятельность, вызывая метод из сервиса каждый раз, когда вызывается fn_update.

Вот мой сервис

class LocationService : Service(), LocationListener {
private var context: Context? = null
internal var isGPSEnable = false
internal var isNetworkEnable = false
internal var latitude: Double = 0.toDouble()
internal var longitude: Double = 0.toDouble()
internal var locationManager: LocationManager? = null
internal var location: Location? = null
private val mHandler = Handler()
private var mTimer: Timer? = null
internal var notify_interval: Long = 3000
var track_lat = 0.0
var track_lng = 0.0
internal lateinit var intent: Intent
override fun onBind(intent: Intent): IBinder? {
    return null
}
override fun onCreate() {
    super.onCreate()
    mTimer = Timer()
    mTimer!!.schedule(TimerTaskToGetLocation(), 5, notify_interval)
    intent = Intent(str_receiver)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    this.context = this
    return Service.START_NOT_STICKY
}

override fun onDestroy() {
    super.onDestroy()
    Log.e(TAG, "onDestroy <<")
    if (mTimer != null) {
        mTimer!!.cancel()
    }
}
private fun trackLocation() {
    Log.e(TAG, "trackLocation")
    val TAG_TRACK_LOCATION = "trackLocation"
    val params = HashMap<String, String>()
    params["latitude"] = "" + track_lat
    params["longitude"] = "" + track_lng
}

override fun onLocationChanged(location: Location) {

}

override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {

}

override fun onProviderEnabled(provider: String) {

}

override fun onProviderDisabled(provider: String) {

}

private fun fn_getlocation() {
    locationManager = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    isGPSEnable = locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER)
    isNetworkEnable = locationManager!!.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    if (!isGPSEnable && !isNetworkEnable) {
        Log.e(TAG, "CAN'T GET LOCATION")
        stopSelf()
    } else {
        if (isNetworkEnable) {
            location = null
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && 
                        checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                }
            }
            locationManager!!.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 0f, this)
            if (locationManager != null) {
                location = locationManager!!.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                if (location != null) {
                    Log.e(TAG, "isNetworkEnable latitude" + location!!.latitude + "\nlongitude" + location!!.longitude + "")
                    latitude = location!!.latitude
                    longitude = location!!.longitude
                    track_lat = latitude
                    track_lng = longitude
                    fn_update(location!!);
                }
            }
        } else if (isGPSEnable) {
            location = null
            locationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0f, this)
            if (locationManager != null) {
                location = locationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                if (location != null) {
                    Log.e(TAG, "isGPSEnable latitude" + location!!.latitude + "\nlongitude" + location!!.longitude + "")
                    latitude = location!!.latitude
                    longitude = location!!.longitude
                    track_lat = latitude
                    track_lng = longitude
                    fn_update(location!!);
                }
            }
        }
        trackLocation()
    }
}

private inner class TimerTaskToGetLocation : TimerTask() {
    override fun run() {
        mHandler.post { fn_getlocation() }
    }
}}

и это моя деятельность

  @RequiresApi(api = Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val background = Intent(this, LocationService::class.java)

    this.startService(background)

Пожалуйста, помогите мне Как я могу отозвать сервис и передать данные в деятельность ..

Заранее спасибо

1 Ответ

0 голосов
/ 30 октября 2019

Есть много статей, как это сделать.

Например, вы можете проверить этот ответ - https://stackoverflow.com/a/7283298/9522749

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...