Buscar..


Sintaxis

  1. <service android: name = ". UploadS3IntentService" android: export = "false" />

Observaciones

Un IntentService proporciona una forma sencilla de descargar el trabajo en un hilo de fondo. Se encarga de todo acerca de recibir solicitudes, ponerlas en una cola, detenerse, etc. para usted. También es fácil de implementar, por lo que es perfecto para usar cuando tienes operaciones que requieren mucho tiempo y no pertenecen al subproceso principal (UI).

Creando un IntentService

Para crear un IntentService, cree una clase que extienda IntentService , y dentro de él, un método que onHandleIntent :

package com.example.myapp;
public class MyIntentService extends IntentService {
    @Override
     protected void onHandleIntent (Intent workIntent) {
         //Do something in the background, based on the contents of workIntent.
     }
}

Ejemplo de servicio de intenciones

Aquí hay un ejemplo de un IntentService que pretende cargar imágenes en segundo plano. Todo lo que necesita hacer para implementar un IntentService es proporcionar un constructor que llame al constructor super(String) , y debe implementar el onHandleIntent(Intent) .

public class ImageLoaderIntentService extends IntentService {

    public static final String IMAGE_URL = "url";

    /**
     * Define a constructor and call the super(String) constructor, in order to name the worker
     * thread - this is important if you want to debug and know the name of the thread upon 
     * which this Service is operating its jobs.
     */
    public ImageLoaderIntentService() {
        super("Example");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // This is where you do all your logic - this code is executed on a background thread

        String imageUrl = intent.getStringExtra(IMAGE_URL);

        if (!TextUtils.isEmpty(imageUrl)) {
            Drawable image = HttpUtils.loadImage(imageUrl); // HttpUtils is made-up for the example
        }

        // Send your drawable back to the UI now, so that you can use it - there are many ways
        // to achieve this, but they are out of reach for this example
    }
}

Para iniciar un IntentService , debes enviarle un Intent . Puedes hacerlo desde una Activity , por ejemplo. Por supuesto, no estás limitado a eso. Este es un ejemplo de cómo convocarías a tu nuevo Service de una clase de Activity .

Intent serviceIntent = new Intent(this, ImageLoaderIntentService.class); // you can use 'this' as the first parameter if your class is a Context (i.e. an Activity, another Service, etc.), otherwise, supply the context differently
serviceIntent.putExtra(IMAGE_URL, "http://www.example-site.org/some/path/to/an/image");
startService(serviceIntent); // if you are not using 'this' in the first line, you also have to put the call to the Context object before startService(Intent) here

El IntentService procesa los datos de su Intent s de manera secuencial, de modo que puede enviar múltiples Intent sin preocuparse de si van a chocar entre sí. Solo se procesa una Intent a la vez, el resto va en una cola. Cuando todos los trabajos estén completos, el IntentService se cerrará automáticamente.

Ejemplo de IntentService Básico

La clase abstracta IntentService es una clase base para servicios, que se ejecuta en segundo plano sin ninguna interfaz de usuario. Por lo tanto, para actualizar la interfaz de usuario, tenemos que hacer uso de un receptor, que puede ser un BroadcastReceiver o un ResultReceiver :

  • Se debe usar un BroadcastReceiver si su servicio necesita comunicarse con múltiples componentes que desean escuchar la comunicación.
  • Un ResultReceiver : debe usarse si su servicio necesita comunicarse solo con la aplicación principal (es decir, su aplicación).

Dentro del IntentService , tenemos un método clave, onHandleIntent() , en el que realizaremos todas las acciones, por ejemplo, preparar notificaciones, crear alarmas, etc.

Si desea utilizar su propio IntentService , debe ampliarlo de la siguiente manera:

public class YourIntentService extends IntentService {
    public YourIntentService () {
        super("YourIntentService ");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // TODO: Write your own code here.
    }
}    

Llamar / comenzar la actividad se puede hacer de la siguiente manera:

Intent i = new Intent(this, YourIntentService.class);
startService(i);  // For the service.
startActivity(i); // For the activity; ignore this for now.

De manera similar a cualquier actividad, puede pasarle información adicional como los datos del paquete de la siguiente manera:

Intent passDataIntent = new Intent(this, YourIntentService.class);
msgIntent.putExtra("foo","bar");
startService(passDataIntent);

Ahora suponga que pasamos algunos datos a la clase YourIntentService . Sobre la base de estos datos, una acción se puede realizar de la siguiente manera:

public class YourIntentService extends IntentService {
    private String actvityValue="bar";
    String retrivedValue=intent.getStringExtra("foo");

    public YourIntentService () {
        super("YourIntentService ");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if(retrivedValue.equals(actvityValue)){
            // Send the notification to foo.
        } else {
            // Retrieving data failed.
        }    
    }
}

El código anterior también muestra cómo manejar las restricciones en el método OnHandleIntent() .



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow