Home » Android » How to get coordinates from location when screen is locked ? Android-Exceptionshub

How to get coordinates from location when screen is locked ? Android-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

In my app i’m trying to save coordinates each 3 seconds during workout and i have to do this all time even if screen is locked. So i made a service to do this but i still don’t work. I will really greatfull if someone could take a look :

Service class: 


import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.os.PowerManager

open class GPSlocation : Service() {

lateinit var intent: Intent
lateinit var manager: LocationManager
override fun onBind(intent: Intent?): IBinder? {
    return null
}


@SuppressLint("MissingPermission")
override fun onCreate() {
    manager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0f,
        object : LocationListener {
            override fun onLocationChanged(location: Location?) {
                val intent = Intent("location_update")
                intent.putExtra("coordinates", location)
                sendBroadcast(intent)
            }

            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onProviderEnabled(provider: String?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onProviderDisabled(provider: String?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }
        })
    super.onCreate()

}
}

Next in my fragment in onResume() function i added simply receiver:

 override fun onResume() {
        mBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val location = intent!!.extras!!.get("coordinates") as Location

            }

        }

    activity!!.registerReceiver(mBroadcastReceiver, IntentFilter("location_update"))
super.onResume()
}

And i call it on Create in fragment like this:

 val i = Intent(activity!!.applicationContext,GPSlocation::class.java)
            activity!!.applicationContext.startService(i)

I tried use WakeLock but it didn’t help too.
Thanks for any advice!

How to&Answers: