Android GPS Location Periodically

I want to create an application that selects a user's location every 5 minutes from 9:00 to 21:00. Now I can’t think of flow. I got confused in :

  • Do I have to implement 2 repeating alarm dispatchers, one for every 5 minutes and one for the time interval.?
  • Or do it in a way, fire alarm every 5 min and check if it is between the time interval, and then start the location service and upload to the server.?

Please help me with suggestions / tips. How to achieve this in the best way in terms of phone battery efficiency.

+4
source share
4 answers

Well, you can use Handler to request a location, you can do something like this

 Handler handler = new Handler();
 Runnable runnable = new Runnable() {
        public void run() {
            currentLocation = getCurrentUserLocation();
            handler.postDelayed(this, 1000*60*5);
        }
    }
 };
 handler.postDelayed(runnable, 1000*60*5);

And to check the time interval between them, you can configure the alarm manager for this task,

And once the time limit is reached, you need to remove the handler callbacks

handleLocation.removeCallbacksAndMessages(null);
0
source

Handler.postDelayer() , 30 , . - - 30 , Handler, - AlarmManager ( ).

0

, 1 . -

gradle -

compile 'com.google.android.gms:play-services:9.4.0'

LocationService.class

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.text.SimpleDateFormat;
import java.util.Date;

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {
    protected static final String TAG = "location-updates";
    private static final long day = 24 * 60 * 60 * 1000;
    private static final long hours = 60 * 60 * 1000;
    private static final long minute = 60 * 1000;
    private static final long fiveSec = 5 * 1000;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    @Override
    public void onCreate() {
        super.onCreate();
        mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(minute);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setSmallestDisplacement(0);

        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }


    @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }


    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }

    //Location Listener
    @Override
    public void onLocationChanged(final Location location) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String currentDateandTime = sdf.format(new Date());
        Log.e("Location ", location.getLatitude() + " " + location.getLongitude() + " " + currentDateandTime);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }


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


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        boolean isGranted = false;
        for (int i = 0; i < grantResults.length; i++)
            if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION) && (grantResults[i] == PackageManager.PERMISSION_GRANTED))
                isGranted = true;
        if (isGranted) {
            startService(new Intent(this, LocationService.class));

        } else {

        }
    }
}
0

Source: https://habr.com/ru/post/1680094/


All Articles