2011-03-14 18 views
17

Para comenzar mi servicio desde una Activiy, uso startService(MyService.class). Esto funciona muy bien, pero en un caso especial, el servicio debe iniciarse de manera diferente. Quiero pasar algunos parámetros al inicio del servicio.Android: iniciar el servicio con el parámetro

He intentado lo siguiente en mi Actividad:

Intent startMyService= new Intent(); 
startMyService.setClass(this,LocalService.class); 
startMyService.setAction("controller"); 
startMyService.putExtra(Constants.START_SERVICE_CASE2, true); 

startService(startMyService); 

En mi servicio que utilizo:

public class MyIntentReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(Context context, Intent intent) { 

     if (intent.getAction().equals("controller")) 
     { 
       // Intent was received        
     } 

    } 
} 

El IntentReceiver se ha registrado en onCreate() así:

IntentFilter mControllerIntent = new IntentFilter("controller"); 
MyIntentReceiver mIntentReceiver= new MyIntentReceiver(); 
registerReceiver(mIntentReceiver, mControllerIntent); 

Con esta solución, el servicio se inicia pero no se recibe la intención. ¿Cómo puedo iniciar un servicio y pasar mis parámetros?

Gracias por su ayuda!

+0

¿Para qué es MyIntentReceiver? ¿Desea escuchar una transmisión específica y alterar su comportamiento de servicio? – Audrius

+0

@Audrius: Sí, tienes razón. MyIntentReceiver se usa para cambiar el comportamiento de mi servicio. Hay dos estados en mi servicio: uno al iniciar el servicio y otro cuando el servicio se está ejecutando. – Mike

Respuesta

14

Paso n. ° 1: elimine la implementación de BroadcastReceiver.

Paso # 2: Examine el Intent que su servicio obtiene en onStartCommand() y mire la acción a través de getAction().

+2

Pero esto permitirá cambiar el servicio solo después de onCreate. Deseo pasar la variable en el comando oncreate, luego cómo hacerlo –

24
Intent serviceIntent = new Intent(this,ListenLocationService.class); 
serviceIntent.putExtra("From", "Main"); 
startService(serviceIntent); 
//and get the parameter in onStart method of your service class 

@Override 
public void onStart(Intent intent, int startId) { 
    super.onStart(intent, startId); 
    Bundle extras = intent.getExtras(); 

    if(extras == null) { 
     Log.d("Service","null"); 
    } else { 
     Log.d("Service","not null"); 
     String from = (String) extras.get("From"); 
     if(from.equalsIgnoreCase("Main")) 
      StartListenLocation(); 
    } 
} 
+3

También puede obtener el objeto de intento en el método onStartCommand de la clase de servicio –

+1

, así como en 'onHandleIntent (intención intencionada)' – grim

+0

Ahora está en "onStartCommand" – Ton

Cuestiones relacionadas