Служба определения местоположения карт не обновляется, когда приложение не находится на переднем плане - PullRequest
0 голосов
/ 04 августа 2020

Мое приложение должно отслеживать расстояние до местоположения, даже когда приложение скрыто (например, нажатием кнопки «Домой»), основное действие приложения все еще выполняется, которое может отображать тост-сообщение, однако, когда оно скрыто, расстояние всегда одинаковое даже переместились на сотни метров.

//this is a bound service 
public class TrackLocationService extends Service {
    private static final String TAG = "MapsActivityDbgService";
    private final IBinder binder = new TrackerBinder();
    private static double distanceInMeters;
    private static Location targetLocation = null;
    private LocationListener listener;
    private LocationManager locationManager;

    //define a binder to enable the activity to bind to the tracker service
    public class TrackerBinder extends Binder {
        TrackLocationService getTracker() {
            return TrackLocationService.this;
        }
    }

    public TrackLocationService() {
    }

    public static double getDistanceInMeters() {
        return distanceInMeters;
    }


    @Override
    //this is called when the activity binds to the service
    public IBinder onBind(Intent intent) {
        targetLocation = intent.getParcelableExtra("TARGET_LOCATION");
        return binder;
        //throw new UnsupportedOperationException("Not yet implemented");
    }

    public void onCreate() {
        //initiate the location listener
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                distanceInMeters = location.distanceTo(targetLocation);
                Log.i(TAG, "TrackLocationService location changed");
            }

            public void onProviderDisabled(String arg0) {
            }

            public void onProviderEnabled(String arg0) {
            }

            public void onStatusChanged(String arg0, int arg1, Bundle bundle) {
            }
        };

        //register the location listener
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, listener);
    }

    @Override
    public void onDestroy() {//called when the service is no longer being used and is about to be destoryed
        super.onDestroy();
        if (locationManager!= null && listener != null)
        {
            locationManager.removeUpdates(listener);
            locationManager = null;
            listener = null;
        }
    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;  //run this service always
    }

}

В основном действии запустите вышеуказанный сервис:

                Intent intent = new Intent(this, TrackLocationService.class);
                intent.putExtra("TARGET_LOCATION", targetLocation);
                startService(intent);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);//to get the data from service

С подключением:

private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            TrackLocationService.TrackerBinder trackerBinder = (TrackLocationService.TrackerBinder)service;
            tracker = trackerBinder.getTracker();
            //bBind = true;
            
            Log.i(TAG, "onServicieConnected: " + connection.toString());
                 }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //bBind = false;
            tracker = null;
            Log.i(TAG, "onServiceDisconnected");//never reached?
        }
    };

А затем отслеживайте с обработчиком в основном действии:

    private void monitorDistance()
    {
        final Handler handler=new Handler();

        handler.post(new Runnable(){
            public void run(){
                //tracing the distance
                double distance =0.0;
                if (tracker!=null) {
                   distance = tracker.getDistanceInMeters();
                   Toast.makeText(getApplicationContext(), "Distance: " + (int) distance + "m", LENGTH_LONG).show();
                }
                else
                    {
                        Toast.makeText(getApplicationContext(), "Tracing but no tracer..." + iState, LENGTH_LONG).show();
                }
            }
        });
    }

Благодарю, если кто-нибудь может взглянуть, спасибо!

...