-1

How to send user location data to server every five second using restful API even app is closed in android?

Please help me

Dharmi Patel
  • 55
  • 1
  • 6
  • Your questions are answered here: https://stackoverflow.com/questions/39953053/how-to-find-my-current-location-latitude-longitude-in-every-5-second-in-andr and https://stackoverflow.com/questions/26058424/send-request-to-web-service-every-5-second Although it is not a good idea to do so. Background location limits are listed here by Google: https://developer.android.com/about/versions/oreo/background-location-limits – Iffat Fatima Dec 27 '18 at 09:05
  • no i try to send data even app is close – Dharmi Patel Dec 27 '18 at 09:07
  • You can use service for that purpose or JobScheduler – Iffat Fatima Dec 27 '18 at 09:09
  • 2
    Possible duplicate of [How to find my current location (latitude + longitude) in every 5 second in Android?](https://stackoverflow.com/questions/39953053/how-to-find-my-current-location-latitude-longitude-in-every-5-second-in-andr) – Melvin Otieno Dec 27 '18 at 09:20
  • How can i use JobScheduler for this? – Dharmi Patel Dec 27 '18 at 09:21
  • Here is a nice tutorial of implmenting/using job scheduler: http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html – Hassan Jamil Dec 27 '18 at 10:25

2 Answers2

0

if you want to make your code run even when the app is closed you need to use services, services can run in the background even if the app is closed, and you may need to use a broadcast receiver with the service to keep running it every time it finishes.

this is the Service:

public class myService extends Service {

    public static int counter = 0;
    public myReceiver myReceiver = new myReceiver();

    @Override
    public void onCreate() {
        super.onCreate();
        //this line register the Receiver for the first time
        myService.this.registerReceiver(myReceiver, new IntentFilter("com.example.myApp"));

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //Here you have to put the code that gets the location and send it

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    //here you sent a broadcast message to start the reciever
    //note that the broadcast message that you send has to be unique writing you package name will be fine ex: com.example.myApp
        Intent sendBroadCast = new Intent("com.example.myApp");
        sendBroadcast(sendBroadCast);
    }

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

and this is the broadcast receiver:

public class myReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        if("com.example.myApp".equals(intent.getAction())){
           //the handler is used as a timer here
           Handler handler = new Handler();
           handler.postDelayed(new Runnable() {
               @Override
               public void run() {
                   Intent myServ = new Intent(context, myService.class);
                   try {
                       context.startService(myServ);
                   }catch (Exception e){

                   }
               }
           },5000);
        }
    }
}
amm965
  • 399
  • 5
  • 14
  • please give me code example i am new in android and i also try many code – Dharmi Patel Dec 27 '18 at 09:41
  • a code example for this would be long, you need to get familiar with services and broadcast receivers first, then I can tell how you should implement it, you can find a lot of tutorials on both services and broadcast receivers on youtube. – amm965 Dec 27 '18 at 09:45
  • i know service and broadcast receivers but i don't know how to use it – Dharmi Patel Dec 27 '18 at 09:47
  • i also try some tutorial but its not working please help me – Dharmi Patel Dec 27 '18 at 09:47
  • ok I'll add a code sample on the service/broadcast receiver but without including the location bit, you can find that part in previously answered questions – amm965 Dec 27 '18 at 09:52
  • I've added the code for the service and the broadcast receiver, note that you may need to tweak the code a little bit according to your needs – amm965 Dec 27 '18 at 10:14
0

you can create a background service that it works when user lock screen or close your app from background you must create service with this way: first create a Service class like this:

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks {


public static double latitude;
public static double longitude;

private int retryGPS = 0;
private int retryNetwork = 0;
private Handler handler;
private Runnable runnable;
private GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
private LocationListener[] mLocationListeners = new LocationListener[]{
        new LocationListener(LocationManager.GPS_PROVIDER),
};

private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 1;

private static final String TAG = "LocationService";

@Override
public void onCreate() {

    buildGoogleApiClient();

    initializeLocationManager();

    locationRequest();

    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            sendLocation();
        }
    };

    sendLocation();
}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addApi(LocationServices.API)
            .build();
}

private void initializeLocationManager() {

    if (mLocationManager == null) {
        mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    }
}

private void locationRequest() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
            mLocationListeners[0]);
}


private void sendLocation() {

        //TODO: you can use location here
       handler.postDelayed(runnable,5000);
}

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

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    if (!mGoogleApiClient.isConnected())
        mGoogleApiClient.connect();
    return START_STICKY;
}

@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;
    }
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    } else {
        try {
            Thread.sleep(3000);
            onConnected(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onDestroy() {

    handler.removeCallbacks(runnable);

    if (mLocationManager != null) {
        for (LocationListener mLocationListener : mLocationListeners) {
            try {
                mLocationManager.removeUpdates(mLocationListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    super.onDestroy();
}

private class LocationListener implements android.location.LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {

    Location mLastLocation;

    public LocationListener(String provider) {

        Log.d(TAG, "LocationListener: " + provider);
        mLastLocation = new Location(provider);
    }

    @Override
    public void onLocationChanged(final Location location) {

        mLastLocation.set(location);
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Log.d(TAG, "onLocationChanged: { latitude: " + latitude + " ,longitude: " + longitude + " , accuracy: " + location.getAccuracy() + " }");
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.d(TAG, "onProviderDisabled: " + provider);
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.d(TAG, "onProviderEnabled: " + provider);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d(TAG, "onStatusChanged: " + status);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    }

}

}

then register service in manifest:

 <service
        android:name=".service.LocationService"
        android:enabled="true"
        android:process=":process" />

then start service from any activity or fragment :

public static void mStopService(Context context) {
    context.stopService(new Intent(context, LocationService.class));
}

public static void mStartService(Context context) {
    context.startService(new Intent(context, LocationService.class));
}
saeedata
  • 901
  • 6
  • 14