Estoy buscando la forma de que una aplicación en segundo plano continúe trasmitiendo la ubicación a la base de datos y no se corte. He llegado al punto en el que se pone en segundo plano pero no envía ubicaciones.
Adjunto código, la clase Main
y mi clase Ubicacion
.
Main
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
LocationListener {
private static final String LOGTAG = "android-localizacion";
private static final int PETICION_PERMISO_LOCALIZACION = 101;
private static final int PETICION_CONFIG_UBICACION = 201;
public static final int RC_SIGN_IN = 1;
private GoogleApiClient apiClient;
private TextView lblLatitud;
private TextView lblLongitud;
private ToggleButton btnActualizar;
private LocationRequest locRequest;
private FirebaseDatabase database;
private DatabaseReference myRef;
public String matricula = "test";
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseUser user;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.sign_out_menu:
AuthUI.getInstance().signOut(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
lblLatitud = (TextView) findViewById(R.id.lblLatitud);
lblLongitud = (TextView) findViewById(R.id.lblLongitud);
btnActualizar = (ToggleButton) findViewById(R.id.btnActualizar);
btnActualizar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggleLocationUpdates(btnActualizar.isChecked());
startService(new Intent(MainActivity.this,
UbiServ.class));
}
});
//Construcción cliente API Google
apiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null) {
matricula = user.getDisplayName();
Toast.makeText(MainActivity.this, "Ok, ja estàs loggetjat", Toast.LENGTH_LONG).show();
} else {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder().setIsSmartLockEnabled(false)
.setAvailableProviders(
Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()
))
.build(),
RC_SIGN_IN);
}
}
};
}
private void toggleLocationUpdates(boolean enable) {
if (enable) {
enableLocationUpdates();
} else {
disableLocationUpdates();
}
}
private void enableLocationUpdates() {
locRequest = new LocationRequest();
locRequest.setInterval(2000);
locRequest.setFastestInterval(1000);
locRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest locSettingsRequest =
new LocationSettingsRequest.Builder()
.addLocationRequest(locRequest)
.build();
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(
apiClient, locSettingsRequest);
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(LOGTAG, "Configuración correcta");
startLocationUpdates();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
Log.i(LOGTAG, "Se requiere actuación del usuario");
status.startResolutionForResult(MainActivity.this, PETICION_CONFIG_UBICACION);
} catch (IntentSender.SendIntentException e) {
btnActualizar.setChecked(false);
Log.i(LOGTAG, "Error al intentar solucionar configuración de ubicación");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.i(LOGTAG, "No se puede cumplir la configuración de ubicación necesaria");
btnActualizar.setChecked(false);
break;
}
}
});
}
private void disableLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
apiClient, this);
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//Ojo: estamos suponiendo que ya tenemos concedido el permiso.
//Sería recomendable implementar la posible petición en caso de no tenerlo.
Log.i(LOGTAG, "Inicio de recepción de ubicaciones");
LocationServices.FusedLocationApi.requestLocationUpdates(
apiClient, locRequest, MainActivity.this);
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
//Se ha producido un error que no se puede resolver automáticamente
//y la conexión con los Google Play Services no se ha establecido.
Log.e(LOGTAG, "Error grave al conectar con Google Play Services");
}
@Override
public void onConnected(@Nullable Bundle bundle) {
//Conectado correctamente a Google Play Services
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PETICION_PERMISO_LOCALIZACION);
} else {
Location lastLocation =
LocationServices.FusedLocationApi.getLastLocation(apiClient);
updateUI(lastLocation);
}
}
@Override
public void onConnectionSuspended(int i) {
//Se ha interrumpido la conexión con Google Play Services
Log.e(LOGTAG, "Se ha interrumpido la conexión con Google Play Services");
}
private void updateUI(Location loc) {
if (loc != null) {
lblLatitud.setText("Latitud: " + String.valueOf(loc.getLatitude()));
lblLongitud.setText("Longitud: " + String.valueOf(loc.getLongitude()));
saveLocation(loc);
} else {
lblLatitud.setText("Latitud: (desconocida)");
lblLongitud.setText("Longitud: (desconocida)");
}
}
public void saveLocation (Location loc)
{
myRef = database.getReference("root");
Ubicacion last = new Ubicacion(loc.getLatitude(), loc.getLongitude(), loc.getTime());
myRef.child(matricula).push().setValue(last);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PETICION_PERMISO_LOCALIZACION) {
if (grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permiso concedido
@SuppressWarnings("MissingPermission")
Location lastLocation =
LocationServices.FusedLocationApi.getLastLocation(apiClient);
updateUI(lastLocation);
} else {
//Permiso denegado:
//Deberíamos deshabilitar toda la funcionalidad relativa a la localización.
Log.e(LOGTAG, "Permiso denegado");
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RC_SIGN_IN:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Estàs autenticat", Toast.LENGTH_SHORT).show(); }
// matricula = user.getDisplayName();
else if (resultCode == RESULT_CANCELED)
{
Toast.makeText(this, "Adeu!", Toast.LENGTH_SHORT).show();
finish();
}
break;
case PETICION_CONFIG_UBICACION:
switch (resultCode) {
case Activity.RESULT_OK:
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Log.i(LOGTAG, "El usuario no ha realizado los cambios de configuración necesarios");
btnActualizar.setChecked(false);
break;
}
break;
}
}
@Override
public void onLocationChanged(Location location) {
Log.i(LOGTAG, "Recibida nueva ubicación!");
//Mostramos la nueva ubicación recibida
updateUI(location);
}
@Override
protected void onPause() {
super.onPause();
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
@Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}
Ubicacion Service
public class UbiServ extends Service implements GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
LocationListener {
private static final String LOGTAG = "android-localizacion";
public static final int RC_SIGN_IN = 1;
private GoogleApiClient apiClient;
private TextView lblLatitud;
private TextView lblLongitud;
private LocationRequest locRequest;
private FirebaseDatabase database;
private DatabaseReference myRef;
public String matricula = "test";
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseUser user;
@Override
public void onCreate() {
Toast.makeText(this, "Servicio ONCREATE ",
Toast.LENGTH_SHORT).show();
super.onCreate();
/* mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null) {
matricula = user.getDisplayName();
Toast.makeText(UbiServ.this, "Ok, ja estàs loggetjat", Toast.LENGTH_LONG).show();
}
}
};
*/
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Servicio arrancado ",
Toast.LENGTH_SHORT).show();
database = FirebaseDatabase.getInstance();
this.mFirebaseAuth = FirebaseAuth.getInstance();
matricula = this.mFirebaseAuth.getCurrentUser().getDisplayName();
//Construcción cliente API Google
apiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onConnected(@Nullable Bundle bundle) {
//Conectado correctamente a Google Play Services
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
/*ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PETICION_PERMISO_LOCALIZACION);*/
} else {
enableLocationUpdates();
Location lastLocation =
LocationServices.FusedLocationApi.getLastLocation(apiClient);
updateUI(lastLocation);
}
}
@Override
public void onConnectionSuspended(int i) {
//Se ha interrumpido la conexión con Google Play Services
Log.e(LOGTAG, "Se ha interrumpido la conexión con Google Play Services");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
//Se ha producido un error que no se puede resolver automáticamente
//y la conexión con los Google Play Services no se ha establecido.
Log.e(LOGTAG, "Error grave al conectar con Google Play Services");
}
@Override
public void onLocationChanged(Location location) {
Log.i(LOGTAG, "Recibida nueva ubicación!");
//Mostramos la nueva ubicación recibida
updateUI(location);
}
private void updateUI(Location loc) {
if (loc != null) {
lblLatitud.setText("Latitud: " + String.valueOf(loc.getLatitude()));
lblLongitud.setText("Longitud: " + String.valueOf(loc.getLongitude()));
saveLocation(loc);
} else {
lblLatitud.setText("Latitud: (desconocida)");
lblLongitud.setText("Longitud: (desconocida)");
}
}
private void toggleLocationUpdates(boolean enable) {
if (enable) {
enableLocationUpdates();
} else {
//disableLocationUpdates();
}
}
private void enableLocationUpdates() {
locRequest = new LocationRequest();
locRequest.setInterval(2000);
locRequest.setFastestInterval(1000);
locRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
startLocationUpdates();
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(UbiServ.this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//Ojo: estamos suponiendo que ya tenemos concedido el permiso.
//Sería recomendable implementar la posible petición en caso de no tenerlo.
Log.i(LOGTAG, "Inicio de recepción de ubicaciones");
LocationServices.FusedLocationApi.requestLocationUpdates(
apiClient, locRequest, UbiServ.this);
}
}
public void saveLocation(Location loc) {
myRef = database.getReference("root");
Ubicacion last = new Ubicacion(loc.getLatitude(), loc.getLongitude(), loc.getTime());
myRef.child(matricula).push().setValue(last);
}
}
Gracias de antemano.