Android Service está creando una y otra vez
Tengo un botón en el que se escribe el siguiente código
Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, 10); Intent intent = new Intent(Formact.this, MyService.class); MyService.pintent = PendingIntent.getService(Formact.this, 0, intent, 0); MyService.alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); MyService.alarm.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 5000, MyService.pintent);
Ahora una vez que los servicios se crean tiene que destruir en una acción específica pero después de cada vez que la destruye comienza otra vez. Aquí está mi clase de servicio
- Si android reinicia un servicio es onCreate llamado de nuevo?
- ¿Qué es un JobService en Android?
- ¿Qué significa android: enabled para un servicio?
- Android Service ha filtrado a pesar de que es (supuestamente) no se ejecuta
- Android verificar el estado WIFI (desconectado o el usuario ha cambiado WIFI) ¿Cómo FLAG?
public class MyService extends Service { public static int counter = 0; public static PendingIntent pintent; public static AlarmManager alarm; Boolean save=false; public MyService() { } @Override public IBinder onBind(Intent intent) { return new Binder() ; } @Override public void onCreate() { Toast.makeText(this, "Service was Created", Toast.LENGTH_SHORT).show(); } @Override public void onStart(Intent intent, int startId) { counter++; Toast.makeText(this, " Service Started" + " " + counter, Toast.LENGTH_SHORT).show(); SaveForm handler = new SaveForm(getApplicationContext()); handler.setobj(getApplicationContext()); handler.setText(Formact.sendform, Formact.listString); handler.stratConnection(); String m = ""; int val = 0; try{ Log.e("val",SaveForm.msg); if(SaveForm.msg!=null) { m=SaveForm.msg.substring(SaveForm.msg.length() - 1); } val=Integer.parseInt(m); Log.e("val",m); if(val>0) { Toast toast = Toast.makeText(getApplicationContext(), "Data saved", 100); toast.show(); save=true; MyService.this.stopSelf(); // alarm.cancel(pintent); if(alarm!=null) { try{ alarm.cancel(pintent); } catch(Exception e) { Toast toasdst = Toast.makeText(getApplicationContext(), "Massi", 100); toasdst.show(); } alarm=null; } } } catch(Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "Data Not saved", 100); toast.show(); ///responseStr = responseStrr; } } @Override public void onDestroy() { Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show(); super.onDestroy(); if(save) { try{ stopSelf(); } catch(Exception e) { Toast.makeText(this, "Head Bang", Toast.LENGTH_SHORT).show(); super.onDestroy(); } } } }
Había puesto la alarm.cancle pero lanza la excepción porque la alarma ya es nula
Yo también había probado esto
@Override public int onStartCommand(Intent intent, int flags, int startId) { try{ // String parameter = intent.getStringExtra("param_name"); if(save){ stopSelf(); } }catch(Exception ex){ } return startId; }
Pero nada funciona el servicio comienza una y otra vez. Una cosa más si no cerré la aplicación de que todo funciona perfecto la alarma se cancela, pero cuando cierro la aplicación y espero ejecutarlo mismo fondo que empezar a crear una y otra vez.
Ayuda por favor.
- Android: ¿Cuándo usar Service vs Singleton?
- BroadcastReceiver cuando se cambia el estado de la red wifi o 3g
- El servicio exportado no requiere permiso: ¿qué significa?
- ¿Puede alguien explicar cuál es la diferencia entre el servicio no enlazado y enlazado en android
- Empleos para GCM Network Manager
- El servicio USSD no funciona
- ¿Cómo puedo llamar a startIntentSenderForResult en el servicio correctamente?
- Notificación RemoteView en el oyente de clics
Mientras almacena los datos en el servidor
handler.setText(Formact.sendform, Formact.listString);
Simplemente una vez que se guardan los datos,
Formact.sendform=null Formact.listString=null
Cuando estos valores son nulos, la aplicación lanzará una excepción atraparla en un bloque catch y usar esta línea para cerrar
MyService.alarm.cancel(MyService.pintent); MyService.this.stopService();
El servicio no se iniciará de nuevo.
1. No utilice onStart()
, en docs:
onStart(Intent intent, int startId) This method was deprecated in API level 5. Implement onStartCommand(Intent, int, int) instead.
Use onStartCommand
en onStartCommand
lugar y return START_NOT_STICKY
o START_STICKY
no startId
.
2. Parece que está iniciando una conexión handler.stratConnection();
Si le estás bindService()
a cualquier cosa a usar bindService()
, entonces necesitas desvincularlo del servicio usando unbindService(mConnection)
. Como se da en los documentos:
Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time.
Si no es obligatorio, devuelve null
en onBind()
.
@Override public IBinder onBind(Intent intent) { return null; }
3. Utilice super.onDestroy()
así:
@Override public void onDestroy() { Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show(); super.onDestroy(); /***** No need to put this as it is already going to be destroyed if(save) { try{ stopSelf(); } catch(Exception e) { Toast.makeText(this, "Head Bang", Toast.LENGTH_SHORT).show(); super.onDestroy(); } } } *****/ }
4. Cancelar la alarma por alarm.cancel(pintent)
antes de llamar a stopSelf()
.
if(alarm!=null) { try{ alarm.cancel(pintent); } catch(Exception e) { Toast toasdst = Toast.makeText(getApplicationContext(), "Massi", 100); toasdst.show(); } alarm=null; } MyService.this.stopSelf();
5. Está utilizando alarm
y pintent
sin inicializarlo. No se inicializa en su código. 6. Detenga el servicio en su actividad utilizando context.stopService(intent)
, utilizando la misma intención que Intent intent = new Intent(Formact.this, MyService.class);
.