No puedo hacer que un servicio funciona correctamente. He creado un Servicio para captar las coordenadas GPS y que las grabe en firebase en una B.D. Esta es la API que utilizo:
compileSdkVersion 30
minSdkVersion 26
Este es el Servicio:
package com.valhondo.delgado.procesionesgps;
import ...
public class ServiciosGPS extends Service {
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
FirebaseFirestore mfirestorgps;
String gmidpasosservicios, erroeservicio;
private LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if ( locationResult == null ) {
return;
}
for ( Location location: locationResult.getLocations() ) {
// grabo la localizacion en la Base de Datos
Map<String, Object> mapgps = new HashMap<>();
mapgps.put( "longuitud", location.getLongitude());
mapgps.put( "latitud", location.getLatitude());
mfirestorgps.collection( "GPS" ).document( gmidpasosservicios ).update( mapgps );
}
}
};
public ServiciosGPS() { }
@Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient( this );
locationRequest = LocationRequest.create();
locationRequest.setInterval( 1000 );
locationRequest.setFastestInterval( 500 );
locationRequest.setPriority( LocationRequest.PRIORITY_HIGH_ACCURACY );
mfirestorgps = FirebaseFirestore.getInstance();
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.hasExtra("paseidpasos")) {
gmidpasosservicios = intent.getStringExtra("paseidpasos");
}
LocationSettingsRequest locationSettingsRequest = new LocationSettingsRequest.Builder()
.addLocationRequest( locationRequest ).build();
SettingsClient settingsClient = LocationServices.getSettingsClient( ServiciosGPS.this );
Task<LocationSettingsResponse> locationSettingsResponseTask = settingsClient.checkLocationSettings( locationSettingsRequest );
locationSettingsResponseTask.addOnSuccessListener( new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// Coordenadas satifactorfias
startlocalizacongps();
}
} );
locationSettingsResponseTask.addOnFailureListener( new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Si falla las coordenadas
erroeservicio = "No hace nada solo si da error. pasa de el";
}
} );
return START_STICKY;
}
@Override
public void onDestroy(){
super.onDestroy();
fusedLocationProviderClient.removeLocationUpdates( locationCallback );
//waitALittle();
stopSelf();
}
private void waitALittle() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void startlocalizacongps() {
if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates( locationRequest, locationCallback, Looper.getMainLooper() );
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Este es el Androidmanifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
......
<service
android:name=".ServiciosGPS"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="location"/>
Y aqui esta el quick de lam cuestion lo que empieza a preocuparme:
1.- Si al Servicio lom llamo Asi:
Intent intentpasos = new Intent(this, ServiciosGPS.class );
intentpasos.putExtra("paseidpasos", gmidpasos);
this.startService( intentpasos );
El servicio funciona, veo que se van grabando las coordenadas en la B.D., pero al pasar a segundo plano el servicio se detiene si vuelves a primer plano sigue funcionando bien. Esto es lo que me da:
I/System.out: Provider contains=> gps,network
V/FA: Recording user engagement, ms: 31072
V/FA: Connecting to remote service
V/FA: Activity paused, time: 3744793
V/FA: Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 2
D/Surface: Surface::disconnect(this=0x7aeb76e000,api=1)
I/GED: ged_boost_gpu_freq, level 100, eOrigin 2, final_idx 31, oppidx_max 31, oppidx_min 0
V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = android.view.ViewRootImpl@62a38db, this = DecorView@ae0268c[PasosActivity]
D/FA: Application going to the background
V/FA: Inactivity, disconnecting from the service
V/FA: Activity resumed, time: 3762960
V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl@62a38db, this = DecorView@ae0268c[PasosActivity]
D/Surface: Surface::connect(this=0x7aeb76e000,api=1)
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
D/Surface: Surface::setBufferCount(this=0x7aeb76e000,bufferCount=3)
D/Surface: Surface::allocateBuffers(this=0x7aeb76e000)
V/FA: Connecting to remote service
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.valhondo.delgado.procesionesgps activity: com.valhondo.delgado.procesionesgps.Pasos.PasosActivity@b5cda41
I/chatty: uid=10405(com.valhondo.delgado.procesionesgps) identical 2 lines
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.valhondo.delgado.procesionesgps activity: com.valhondo.delgado.procesionesgps.Pasos.PasosActivity@b5cda41
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.valhondo.delgado.procesionesgps activity: com.valhondo.delgado.procesionesgps.Pasos.PasosActivity@b5cda41
I/chatty: uid=10405(com.valhondo.delgado.procesionesgps) identical 4 lines
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.valhondo.delgado.procesionesgps activity: com.valhondo.delgado.procesionesgps.Pasos.PasosActivity@b5cda41
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.valhondo.delgado.procesionesgps activity: com.valhondo.delgado.procesionesgps.Pasos.PasosActivity@b5cda41
I/chatty: uid=10405(com.valhondo.delgado.procesionesgps) identical 8 lines
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.valhondo.delgado.procesionesgps activity: com.valhondo.delgado.procesionesgps.Pasos.PasosActivity@b5cda41
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 1
V/FA: Inactivity, disconnecting from the service
2 Si pòr el contrario lo llamo asi:
Intent intentpasos = new Intent(this, ServiciosGPS.class );
intentpasos.putExtra("paseidpasos", gmidpasos);
this.startForegroundService(intentpasos);
Empieza bien incluido en segundom plano pero a los 5 segundo se sale y me da este error:
I/System.out: Provider contains=> gps,network
I/.procesionesgp: Thread[7,tid=15595,WaitingInMainSignalCatcherLoop,Thread*=0x7b53ac1400,peer=0x14a802f0,"Signal Catcher"]: reacting to signal 3
I/.procesionesgp: Wrote stack traces to tombstoned
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.valhondo.delgado.procesionesgps, PID: 15582
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{9aa65e2 u0 com.valhondo.delgado.procesionesgps/.ServiciosGPS}
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2000)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7561)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
He leido en la documentacion que al utilizar startForegroundService hay que utilizar esta funcion startForeground() dentro del Servicio, sino a los 5 segundo te da este error: "Si una aplicación orientada al nivel de API 28 o versiones posteriores intenta crear un servicio en primer plano sin solicitar FOREGROUND_SERVICE, se genera una SecurityException en el sistema"
POR FAVOR, me podeis dar una solucion para que pueda crear un servicio que pueda pedir las coordenadas GPS y grabarlas en una B.D. y que pueda utilizarse en SEGUNDO PLANO.
Muchas gracias.