'how to create a service or process that updates location in background when application is in background?

i need a method to continuously get location updates in my application even when my application is in background. i have tried using Service and BroadcastReceiver but when application goes into background, location updates are stopped. here is my Code with boradcast Receiver:-

MainActivity:

class MainActivity : AppCompatActivity() {

    companion object {
        private var instance: MainActivity? = null
        fun getMainInstance(): MainActivity? {
            return instance
        }
    }

    private lateinit var client: FusedLocationProviderClient
    private lateinit var request: LocationRequest

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        instance = this
        client = LocationServices.getFusedLocationProviderClient(applicationContext)
        request = LocationRequest.create()
        request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        request.interval = 1000
        request.fastestInterval = 1000
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(
                    android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION
                ), 2201
            )
        } else {
            client.requestLocationUpdates(request, getPendingIntent()!!)
        }
    }

    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext, "paused", Toast.LENGTH_SHORT).show()
    }

    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext, "stopped", Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        client.removeLocationUpdates(getPendingIntent()!!)
        Toast.makeText(applicationContext, "destroyed", Toast.LENGTH_SHORT).show()
    }

    fun toastMessage(location: String) {
        this.runOnUiThread {
            Toast.makeText(
                this,
                location,
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    private fun getPendingIntent(): PendingIntent? {
        val intent = Intent(this,MyLocationReceiver::class.java)
        intent.setAction(MyLocationReceiver.ACTION_PROCESS_UPDATE)
        return PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
    }
}

BroadcastReceiver:

class MyLocationReceiver : BroadcastReceiver() {

    companion object{
        val ACTION_PROCESS_UPDATE = "com.example.backgroundlocation.UPDATE_LOCATION"
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        if(intent != null) {
            val action = intent.action
            if (action.equals(ACTION_PROCESS_UPDATE) && LocationResult.hasResult(intent)){
                val locationResult = LocationResult.extractResult(intent)
                try {
                    Log.d("onLocationReceived", locationResult.toString())
                    //MainActivity.getMainInstance()?.toastMessage(locationResult.toString())
                } catch (e: Exception) {
                    Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show()
                }
            } else {
                //MainActivity.getMainInstance()?.toastMessage("no result")
            }
        }
    }
}

to me, the solution to this seems impossible. Is there any way to update location when application is in background ? Kindly help me out!



Solution 1:[1]

To access the location while in the background you need to get this permission as well from the user in the Manifest

<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

While giving the permission user needs to select allow all the time for location.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jawad