Started Service

Started Service
- Componentes de aplicaciones, ejecutan operaciones en background.
- No dispone de interfaz de usuario (no necesitan de su interacción).
- Posibles usos:
- Reproducción de música
- Descarga/escritura de un fichero
- Dos tipos:
- Started
- Bound
- Se pueden compartir entre actividades (manifest)
- Comparten thread con actividad principal
Started Service
- Se inicia desde una actividad mediante el método startService().
- Puede continuar existiendo aunque la actividad se destruya.
- Puede finalizar cuando termine su acción o la actividad así se lo indique.
- Orientado a ser usado por la actividad padre.
- Se tienen que implementar los métodos principales
Started Service
- onCreate():
- Creación del servicio (una vez)
- onStartCommand():
- Inicio del servicio (una vez por cada llamada de startService)
- Retorno START_STICKY, START_NOT_STICKY
- onBind():
- No sirve para un started service, pero es necesario
- onDestroy():
- Destrucción del servicio
Started Service
- START_STICKY
- El sistema intentará crear el servicio otra vez cuando se haya destruido.
- START_NOT_STICKY
- El sistema no intentara crear el servicio otra vez cuando se haya destruido.
- START_REDELIVER_INTENT
- El sistema intentará crear el servicio otra vez e intentará entregar de nuevo el intent.
Started Service

Started Service
Añadirlo al manifest:
<service android:name=".MyService">
<intent-filter>
<action android:name="MYSERVICE"></action>
</intent-filter>
</service>
Creación
public class MyService extends Service {
@Override
public void onCreate(){
//TODO inicializaciones únicas
}
@Override
public int onStartCommand(Intent intent){
//TODO código principal, se ejecutará cada vez que
//se inicie el servicio desde una actividad
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//No es necesario nada más
return null;
}
@Override
public void onDestroy(){
//TODO código para liberar recursos
//StopSelf() o StopService()
}
}
Utilización
- Crear Intent + llamadas
- Dos opciones:
- Intent intent = new Intent("MYSERVICE");
- En caso de haber declarado el intent-filter
- Intent intent = new Intent (MyActivity.this,MyService.class);
- Intent intent = new Intent("MYSERVICE");
- startService(Intent);
- stopService(Intent);
Utilización
Sólo será creado una vez.
Las siguientes llamadas a startService, ejecutan onStartCommand

22 - Started Service
By androidjedi
22 - Started Service
- 467