-1

what is the best way to get user location after each two minute even you app is killed thanks in advance

Nisar Ahmad
  • 160
  • 1
  • 6

5 Answers5

3

Follow This Steps

1) Write Those code in your manifest file.Create Broadcast receiver and service.

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

   <receiver
   android:name=".activity.Timerservice"
   android:process=":remote" >
   </receiver>

   <service
   android:name=".model.GPSTracker"
   android:exported="false" />

2) In your Main Activity create on method.for continues fix interval time get current lat-long

public void scheduleAlarm() {
    // Construct an intent that will execute the AlarmReceiver
    Intent intent = new Intent(getApplicationContext(), Timerservice.class);
    // Create a PendingIntent to be triggered when the alarm goes off
    pIntent = PendingIntent.getBroadcast(this, Timerservice.REQUEST_CODE,
            intent, PendingIntent.FLAG_UPDATE_CURRENT);
    // Setup periodic alarm every 5 seconds
    long firstMillis = System.currentTimeMillis(); // alarm is set right away
    alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
    // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
            60000, pIntent);

}

3)TimeService.java (Broadcast Receiver class)

public class Timerservice  extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
Context mContext;
public static final String ACTION = "com.codepath.example.servicesdemo.alarm";

// Triggered by the Alarm periodically (starts the service to run task)
@Override
public void onReceive(Context context, Intent intent) {


    final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if ( !manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
        Intent i1 = new Intent(context, AlertDialogActivity.class);
        i1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i1);
        //   buildAlertMessageNoGps();
    }else{
        Intent i = new Intent(context, GPSTracker.class);
        context.startService(i);
    }
}

}

4)GPSTracker.class

public class GPSTracker extends Service implements LocationListener {
Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

double Lastlatitude; // latitude
double Lastlongitude; // longitude

double totalDistance, Totalkm;

SessionManagement sessionManagement;

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker() {
    //super("GPS");
}
public GPSTracker(Context mContext) {
    //super("");
    this.mContext = mContext;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        Criteria locationCritera = new Criteria();
        String providerName = locationManager.getBestProvider(locationCritera,
                true);
        if (providerName != null)
            location = locationManager.getLastKnownLocation(providerName);

        GPSTracker locationListener = new GPSTracker();

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                0, locationListener);


        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider

            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        Log.i("location", +latitude + " " + longitude);
                        // Toast.makeText(getApplicationContext(),"LatLang is" +latitude+" "+longitude,Toast.LENGTH_LONG).show();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}


@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        this.location = location;
        getLatitude();
        getLongitude();
    }
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}


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

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

}
@Override
public void onDestroy() {
    super.onDestroy();
}
Viveka Patel
  • 676
  • 6
  • 17
0

You can choose to use a Background Service for your activity.

Within this service, you set your service to poll for your location at the interval you wish.

After which, you can use LocalBroadcastManager to broadcast the result of your interest to return the useful results to your application.

Hope it helps!

Cheers! Happy Programming!

sihao
  • 433
  • 2
  • 11
0

Use a Started service to run code in the background even when the app is killed. Use a Timer and Timer task to run your location gathering code at specified intervals.

Timer example

new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {}
        }, 0, 1000);
J Whitfield
  • 755
  • 12
  • 22
0

Apart from what J Whitfield and sihao have suggested, You can also make your service as a Start service (not an Intent Service). Then on the onStartCommand of service, return START_STICKY.

You can also try to run your service in separate process so it won't be killed even if your app is killed.

am110787
  • 306
  • 1
  • 2
  • 9
0

Background Service Example Android

Use a Android Service to run code in the background even when the app is killed. Use a BroadcasteReceiver to restart the service when app is killed by user and Android JobService to run your location gathering code at specified intervals.

Try This its working for me getting the location when app is in killed state

Android-Background-Services-Exmaple

https://github.com/surenderkhowal/Android-Background-Services-Exmaple

Surender Kumar
  • 954
  • 16
  • 15