In the example below, you can receive location updates when the application runs in the background every 5 seconds using PRIORITY_HIGH_ACCURACY mode. You will see these updates when you receive notifications of your location coordinates.
I also wanted to check if updates could be received after the application was killed by the system, as indicated here :
public abstract PendingResult requestLocationUpdates (GoogleApiClient client, LocationRequest request, PendingIntent callback)
This method is suitable for use in the background, especially for receiving location updates , even when the application has been killed by the system . To do this, use PendingIntent for the running service.
therefore, I called System.exit (0) in the onBackPressed () Method of Activity, which of course you can skip.
Service:
public class LocationService extends IntentService{ private static final String INTENT_SERVICE_NAME = LocationService.class.getName(); public LocationService() { super(INTENT_SERVICE_NAME); } @Override protected void onHandleIntent(Intent intent) { if (null == intent) { return; } Bundle bundle = intent.getExtras(); if (null == bundle) { return; } Location location = bundle.getParcelable("com.google.android.location.LOCATION"); if (null == location) { return; } if (null != location) {
}
Activity:
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{ private GoogleApiClient googleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); googleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } @Override public void onStart() { super.onStart(); googleApiClient.connect(); } @Override public void onStop() { super.onStop(); if (googleApiClient.isConnected()) { googleApiClient.disconnect(); } } @Override public void onBackPressed() {
}
Resolution in manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
source share