1
class LocationService : Service() {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        intent?.let { it ->
            val action = it.action
            action?.let { it2 ->
                if (it2 == Constant.ACTION_START_LOCATION_SERVICE)
                    startLocationService()
                else if (it2 == Constant.ACTION_STOP_LOCATION_SERVICE)
                    stopLocationService()
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent?): IBinder? {
        throw UnsupportedOperationException("Not Yet Implemented")
    }

    private val locationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            super.onLocationResult(locationResult)
            val latitude = locationResult.lastLocation.latitude
            val longitude = locationResult.lastLocation.longitude
            Log.d("LocationUpdate", "Latitude: $latitude | Longitude: $longitude")
        }
    }

    @SuppressLint("MissingPermission")
    private fun startLocationService() {
        Log.d("LocationUpdate", "Service Started.")
        val channelId = "location_notification_channel"
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val resultIntent = Intent()
        val pendingIntent = PendingIntent.getActivity(
            applicationContext,
            0,
            resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )
        val builder = NotificationCompat.Builder(applicationContext, channelId).apply {
            setSmallIcon(R.mipmap.ic_launcher)
            setContentTitle("Location Service")
            setDefaults(NotificationCompat.DEFAULT_ALL)
            setContentText("Walking")
            setContentIntent(pendingIntent)
            setAutoCancel(true)
            priority = NotificationCompat.PRIORITY_HIGH
        }


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (notificationManager.getNotificationChannel(channelId) == null) {
                val notificationChannel = NotificationChannel(
                    channelId,
                    "Location Service Channel",
                    NotificationManager.IMPORTANCE_HIGH
                ).apply {
                    description = "This channel is used by location service."
                }
                notificationManager.createNotificationChannel(notificationChannel)
            }
        }


        val locationRequest = LocationRequest.create().apply {
            interval = 4000
            fastestInterval = 2000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

        LocationServices.getFusedLocationProviderClient(this)
            .requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper())
        startForeground(Constant.LOCATION_SERVICE_ID, builder.build())
    }

    private fun stopLocationService() {
        Log.d("LocationUpdate", "Service Stopped.")
        LocationServices.getFusedLocationProviderClient(this)
            .removeLocationUpdates(locationCallback)
        stopForeground(true)
        stopSelf()
    }
}

I tried below solutions but not working:

Background Service is not restarting after killed in oppo, vivo, mi android version 7.1.2

Application background service stopped when swiped up in China Phone

Background service in android is not running some devices like oppo,vivo etc

Background Service Stop when removing app from recent

How to WhiteList app in Doze mode Android 6.0

  • you need to give auto start permission in chinese devices in order to run background process. https://stackoverflow.com/questions/44383983/how-to-programmatically-enable-auto-start-and-floating-window-permissions – karan Dec 06 '21 at 08:43

0 Answers0