Функция onLocationChanged() Не работает в фоновом режиме

#android #kotlin #gps #location #maps

Вопрос:

Я использую следующий код, чтобы узнать текущее местоположение пользователя. Когда приложение находится на переднем плане, оно работает отлично, однако, когда я пытаюсь изменить местоположение в эмуляторе в фоновом режиме, оно не указывает мне местоположение. Что я могу сделать?

 class BackgroundLocation:Service(),LocationListener {


override fun onBind(intent: Intent?) = null

@SuppressLint("MissingPermission")
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    super.onStartCommand(intent, flags, startId)
    val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    val locationListener = BackgroundLocation()
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,10f,locationListener)

    return START_STICKY
}



override fun onLocationChanged(location: Location) {
   println(location.toString())
}

override fun onProviderDisabled(provider: String) {
    
}
override fun onProviderEnabled(provider: String) {
    
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
    
}
 

}

Ответ №1:

В настоящее время вы используете фоновую службу. Он работает при запуске, и как только приложение переходит в фоновый режим, служба останавливается.
для непрерывного обновления в фоновом режиме вам необходимо обновить службу до службы переднего плана.

ForegroundService.java

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String input = intent.getStringExtra("inputExtra");
        createNotificationChannel();
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Foreground Service")
                .setContentText(input)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1, notification);
        //do heavy work on a background thread
        //stopSelf();
        return START_NOT_STICKY;
    }
 

AndroidManifest.xml

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

MainActivity.java

 public void startService() {
    Intent serviceIntent = new Intent(this, ForegroundService.class);
    serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");
    ContextCompat.startForegroundService(this, serviceIntent);
}
 

Если вы используете приложение на Android 10 и выше, вам необходимо запросить фоновое местоположение.

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

Вы можете прочитать все о фоновом расположении, ограничениях ИТ и обслуживании переднего плана здесь — https://developer.android.com/about/versions/oreo/android-8.0-changes
https://developer.android.com/guide/components/services