首页 > 解决方案 > 在后台运行位置更新

问题描述

我有以下功能可以检索设备的当前位置。我的问题是我无法在后台运行此服务(我尝试使用服务意图但无济于事)。

private LocationRequest mLocationRequest;

private long UPDATE_INTERVAL = 10 * 1000;  /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */

 protected void startLocationUpdates() {

    // Create the location request to start receiving updates
    mLocationRequest = new LocationRequest();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

    // Create LocationSettingsRequest object using location request
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(mLocationRequest);
    LocationSettingsRequest locationSettingsRequest = builder.build();

    // Check whether location settings are satisfied
    // https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
    SettingsClient settingsClient = LocationServices.getSettingsClient(this);
    settingsClient.checkLocationSettings(locationSettingsRequest);
    if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){


        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
    }else{
        //  locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);

    }
    // new Google API SDK v11 uses getFusedLocationProviderClient(this)
    getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                    // do work here
                    Log.d("test",locationResult.getLastLocation().toString());
                    onLocationChanged(locationResult.getLastLocation());
                }
            },
            Looper.myLooper());
}


public void onLocationChanged(Location location) {
    // New location has now been determined
    String msg = "Updated Location: " +
            Double.toString(location.getLatitude()) + "," +
            Double.toString(location.getLongitude());
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    // You can now create a LatLng Object for use with maps
}


public void getLastLocation() {
    // Get last known recent location using new Google Play Services SDK (v11+)
    FusedLocationProviderClient locationClient = getFusedLocationProviderClient(this);
    if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){


        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
    }else{
        //  locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);

    }
    locationClient.getLastLocation()
            .addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // GPS location can be null if GPS is switched off
                    if (location != null) {
                        onLocationChanged(location);
                    }
                }
            })


            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d("MapDemoActivity", "Error trying to get last GPS location");
                    e.printStackTrace();
                }
            });
}

目前我通过 startLocationUpdates() 启动位置更新服务;功能。我愿意接受任何建议,只要它们保留服务的当前功能。对不起,如果这个问题看起来很愚蠢,但我对 android 很陌生。

标签: androidandroid-location

解决方案


像这样使用

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
         Intent ServiceG = new Intent(context, ClipboardService.class);
         context.startService(ServiceG);
    } else {
         Intent ServiceG = new Intent(context, ClipboardJobService.class);
         //context.startService(ServiceG);
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
             context.startForegroundService(ServiceG);
         }else {
             context.startService(ServiceG);
         }
    }

推荐阅读