安卓GPS位置不会定期更新



我在服务中使用融合位置 api,每隔几秒钟将 GPS 位置更新到服务器。在 MainActivity 中,我编写了打开 locationSettings.然后 onResume 方法中,我启动了 Service(GpsService.java(。每次位置更新服务类发送广播,并在 onResume(( 方法中接收。但是我只得到一次位置坐标.sendAmblnceGps(( 方法是将位置发送到服务器的位置。

全球定位系统服务.java:

public class GpsService extends Service implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
    com.google.android.gms.location.LocationListener locationListener;
    LocationRequest mLocationRequest;
    private static final long INTERVAL = 100* 50;
    private static final long FASTEST_INTERVAL = 100 * 20;
    GoogleApiClient googleApiClient;
    boolean connected;

    public GpsService() {
        super();
    }
    @Override
    public void onCreate() {
        super.onCreate();
        GoogleApiClient.Builder googleApiClientbuilder=new GoogleApiClient.Builder(GpsService.this).addConnectionCallbacks(GpsService.this).addOnConnectionFailedListener(GpsService.this).addApi(LocationServices.API);
        googleApiClient=googleApiClientbuilder.build();
        googleApiClient.connect();
        Toast.makeText(getApplicationContext(),"service created",Toast.LENGTH_SHORT).show();
    }
    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(100);
    }
    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
                LocationServices.FusedLocationApi.requestLocationUpdates(
                googleApiClient, mLocationRequest,  locationListener);
        Log.d("TAG", "Location update started ..............: ");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Service Command", "Started");
        locationListener = new com.google.android.gms.location.LocationListener()
        {
            @Override
            public void onLocationChanged(Location location) {
                Intent intent = new Intent("location_updates");
                intent.putExtra("lat", location.getLatitude());
                intent.putExtra("longt", location.getLongitude());
                Log.e("location", "lat:" + " " + Double.toString(location.getLatitude()) + " " + "Longt:" + " " + Double.toString(location.getLongitude()));
                sendBroadcast(intent);
                } };
          return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,locationListener);
        if(googleApiClient.isConnected()){
            googleApiClient.disconnect();
        }
        Log.e("Service","Stopped");
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e("Connection failed","Service stopped");
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,locationListener);
        if(googleApiClient.isConnected()){
            googleApiClient.disconnect();
        }
    }
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        createLocationRequest();
        startLocationUpdates();
    }
    @Override
    public void onConnectionSuspended(int i) {
    Log.e("Connection","suspended");
    }
}

主活动.java:

@Override
    protected void onResume() {
        super.onResume();
        if (locationManager == null) {
            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } else {
            gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            if (isConnected()) {
                if (gps_enabled) {
                    progressDialog = new ProgressDialog(MainActivity.this);
                    progressDialog.setMessage("Acquiring your current location");
                    progressDialog.setIndeterminate(true);
                    progressDialog.getWindow().setGravity(Gravity.CENTER);
                    progressDialog.show();
                    Log.e("starting", "service");
                    intent = new Intent(MainActivity.this, GpsService.class);
                    startService(intent);
                    broadcastReceiver = new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context context, Intent intent) {
                            Log.e("starting", "broadcastservice");
                            latitude = Double.toString(intent.getDoubleExtra("lat", 0.0));
                            longitude = Double.toString(intent.getDoubleExtra("longt", 0.0));
                            if (isConnected()) {
                                sendAmblnceGps();
                            } else {
                                progressDialog.cancel();
                                Toast.makeText(getApplicationContext(), "Please enable internet connection", Toast.LENGTH_SHORT).show();
                            }
                             }
                             };
                    Log.e("registering", "broadcastservice");
                    registerReceiver(broadcastReceiver, new IntentFilter("location_updates"));
                             }
                             }
                         else {
                   Toast.makeText(getApplicationContext(),"Enable Internet Connection",Toast.LENGTH_SHORT).show();
                             }
                            }
                             }

您已指定mLocationRequest.setSmallestDisplacement(100); ,因此您需要从初始位置更新的位置至少移动 100 米才能进行新的位置更新。

最新更新