Как включить андроид фоновые обновления местоположения? - PullRequest
0 голосов
/ 20 февраля 2011

Привет всем, Я пишу приложение, которое использует геолокацию для отслеживания пользователя, когда он идет от точки А к точке Б. Вот мой код:

public class LocationTest extends Activity {   
    private static final String[] S = { "out of service", "temporarily unavailable", "available" };
    ArrayList<Location> list = new ArrayList<Location>();
    private TextView output;
    private String best;
    LocationListener locationListener;
    LocationManager mgr;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        output = (TextView) findViewById(R.id.output);

        mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria(); 
        best = mgr.getBestProvider(criteria, true);
        log("\nBest provider is: " + best);

        locationListener = new LocationListener(){
        public void onLocationChanged(Location location){
            dumpLocation(location);
            list.add(location);
        }

        public void onStatusChanged(String provider, int status, Bundle extras){
            log("\nProvider status changed: " + provider + ", status=" + S[status]);
        }

        public void onProviderEnabled(String provider){
            log("\nProvider enabled: " + provider);
        }

        public void onProviderDisabled(String provider){
            log("\nProvider disabled: " + provider);
        }
    };
 }

 @Override
 protected void onResume(){
     super.onResume();
     mgr.requestLocationUpdates(best, 120000, 50, locationListener);
 }

 @Override
 protected void onPause(){
     super.onPause();
     mgr.removeUpdates(locationListener);
     log_gen(list);
}

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

Из того, что я исследовал до сих пор, есть два способа сделать это: использовать фоновый сервис для отслеживания или использовать

requestLocationUpdates (String provider, long minTime, float minDistance, PendingIntent intent)

в сочетании с BroadcastReceiver для продолжения получения обновлений местоположения, даже если пользователь выходит из приложения. Если я правильно понимаю, второй метод будет продолжать работать в фоновом режиме. Может кто-нибудь показать мне в коде, как реализовать BroadcastReceiver с альтернативной версией requestLocationUpdates

Большое спасибо заранее.

1 Ответ

0 голосов
/ 31 июля 2015

Используя приведенный ниже код, вы можете получать периодические обновления местоположения, если вы заинтересованы в непрерывно работающем сервисе, вы можете настроить интервал получения обновлений местоположения, а также вам нужно будет интегрировать сервисы Google Play в ваше приложение, чтобы выполнить следующеекод для работы

public class BackgroundLocationService extends Service implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {

    IBinder mBinder = new LocalBinder();

private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
// Flag that indicates if a request is underway.
private boolean mInProgress;
private static final String TAG = BackgroundLocationService.class
        .getSimpleName();
private Boolean servicesAvailable = false;

public class LocalBinder extends Binder {
    public BackgroundLocationService getServerInstance() {
        return BackgroundLocationService.this;
    }
}

@Override
public void onCreate() {
    super.onCreate();

    mInProgress = false;
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest
            .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(Constants.UPDATE_INTERVAL);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(Constants.FASTEST_INTERVAL);

    servicesAvailable = servicesConnected();

    /*
     * Create a new location client, using the enclosing class to handle
     * callbacks.
     */
    mLocationClient = new LocationClient(this, this, this);

}

private boolean servicesConnected() {

    // Check that Google Play services is available
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);

    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {

        return true;
    } else {

        return false;
    }
}

public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    if (!servicesAvailable || mLocationClient.isConnected() || mInProgress)
        return START_STICKY;

    setUpLocationClientIfNeeded();
    if (!mLocationClient.isConnected() || !mLocationClient.isConnecting()
            && !mInProgress) {
        mInProgress = true;
        mLocationClient.connect();
    }

    return START_STICKY;
}

/*
 * Create a new location client, using the enclosing class to handle
 * callbacks.
 */
private void setUpLocationClientIfNeeded() {
    if (mLocationClient == null)
        mLocationClient = new LocationClient(this, this, this);
}

// Define the callback method that receives location updates
@Override
public void onLocationChanged(final Location location) {
    // Report to the UI that the location was updated
    String msg = Double.toString(location.getLatitude()) + ","
            + Double.toString(location.getLongitude());
    Log.d("debug", msg);

    if (location != null) {
        // location has the latitude and longitude
    }

    // Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

public String getTime() {
    SimpleDateFormat mDateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss", Locale.US);
    return mDateFormat.format(new Date());
}


@Override
public void onDestroy() {
    // Turn off the request flag
    mInProgress = false;
    if (servicesAvailable && mLocationClient != null) {
        mLocationClient.removeLocationUpdates(this);
        // Destroy the current location client
        mLocationClient = null;
    }
    // Display the connection status
    // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new
    // Date()) + ": Disconnected. Please re-connect.",
    // Toast.LENGTH_SHORT).show();
    super.onDestroy();
}

/*
 * Called by Location Services when the request to connect the client
 * finishes successfully. At this point, you can request the current
 * location or start periodic updates
 */
@Override
public void onConnected(Bundle bundle) {

    // Request location updates using static settings
    mLocationClient.requestLocationUpdates(mLocationRequest, this);

}

/*
 * Called by Location Services if the connection to the location client
 * drops because of an error.
 */
@Override
public void onDisconnected() {
    // Turn off the request flag
    mInProgress = false;
    // Destroy the current location client
    mLocationClient = null;
    // Display the connection status
    // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new
    // Date()) + ": Disconnected. Please re-connect.",
    // Toast.LENGTH_SHORT).show();

}

/*
 * Called by Location Services if the attempt to Location Services fails.
 */
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    mInProgress = false;

    /*
     * Google Play services can resolve some errors it detects. If the error
     * has a resolution, try sending an Intent to start a Google Play
     * services activity that can resolve error.
     */
    if (connectionResult.hasResolution()) {

        // If no resolution is available, display an error dialog
    } else {

    }
}

Для интеграции сервисов Google Play, пожалуйста, обратитесь сюда

...