My application contains 6 separated activities, one of them returns GPS coordination, this activity work perfectly when it's open but first I return to the main activity it stops updating location.
details :
I have created a GPS services
and called it in the Manifest.xml
<service android:name=".Services.GPS_Service" />
This is the Service :
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("Longitude", location.getLongitude());
i.putExtra("Latitude", location.getLatitude());
final Date date = new Date(location.getTime());
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
i.putExtra("time", sdf.format(date));
sendBroadcast(i);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, listener);
}
@SuppressLint("MissingPermission")
@Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null) {
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
According to your answers and the phrasing you use: "when it's open but first I return to the main activity" - I am assuming by 'I return to the main activity' you mean that either onBackPressed is involved, or just a simple finish() was called. For that reason, onDestroy was called so your listener gets cancelled, and that why it stops working.