2010-07-20 29 views

Respuesta

29

primer contexto (puede ser Actividad/servicio, etc.)

Usted tiene algunas opciones:

1) el uso del Bundle del Intent:

Intent mIntent = new Intent(this, Example.class); 
Bundle extras = mIntent.getExtras(); 
extras.putString(key, value); 

2) Crear una nuevo paquete

Intent mIntent = new Intent(this, Example.class); 
Bundle mBundle = new Bundle(); 
mBundle.extras.putString(key, value); 
mIntent.putExtras(mBundle); 

3) Utilizar el método putExtra() acceso directo de la Intención

Intent mIntent = new Intent(this, Example.class); 
mIntent.putExtra(key, value); 

nuevo contexto (puede ser Actividad/servicio, etc.)

Intent myIntent = getIntent(); // this getter is just for example purpose, can differ 
if (myIntent !=null && myIntent.getExtras()!=null) 
    String value = myIntent.getExtras().getString(key); 
} 

NOTA: paquetes han "get" y "put "métodos para todos los tipos primitivos, Parcelables y Serializables". Acabo de utilizar cadenas con fines de demostración.

+21

Pero no podemos utilizar el método() getIntent dentro de un servicio. ¿Cómo podemos lograr esto cuando estamos enviando valor de la actividad al servicio? –

+0

cómo obtener el valor int ... – Prakhar

+2

Esto no funciona para los servicios ...? –

156

Para una respuesta precisa a esta pregunta sobre "¿Cómo enviar datos a través de la intención de una actividad de servicio", es que usted tiene que reemplazar el método onStartCommand() que es el que recibe el objeto intención:

Cuando se crea un Service se debe reemplazar el método onStartCommand() por lo que si estrechamente mira la firma a continuación, este es el que recibe el objeto intent que se pasa a la misma:

public int onStartCommand(Intent intent, int flags, int startId) 

lo tanto de una actividad que va a crear la i objeto ntent para iniciar el servicio y luego coloque sus datos dentro del objeto de la intención, por ejemplo, que desea pasar un UserIDActivity-Service:

Intent serviceIntent = new Intent(YourService.class.getName()) 
serviceIntent.putExtra("UserID", "123456"); 
context.startService(serviceIntent); 

Cuando se inicia el servicio de su método onStartCommand() se llamará por lo que en este método se puede recuperar el valor (identificación de usuario) del objeto, por ejemplo, la intención

public int onStartCommand (Intent intent, int flags, int startId) { 
    String userID = intent.getStringExtra("UserID"); 
    return START_STICKY; 
} 

Nota: la respuesta anterior especifica para tener una intención con getIntent() método que no es correcto en el contexto de un servicio

+32

Esto debería haber sido la respuesta aceptada. La respuesta aceptada es incorrecta para el Servicio. – zeeshan

+0

Tengo este error: 'No se puede iniciar el servicio Intención: no encontrado' – fullOfQuestion

9

Si vincula su servicio, obtendrá el extra en onBind(Intent intent).

Actividad:

Intent intent = new Intent(this, LocationService.class);                      
intent.putExtra("tour_name", mTourName);      
bindService(intent, mServiceConnection, BIND_AUTO_CREATE); 

Servicio:

@Override 
public IBinder onBind(Intent intent) { 
    mTourName = intent.getStringExtra("tour_name"); 
    return mBinder; 
} 
+0

¿Funciona esto para los servicios del sistema? –

+0

@ChefPharaoh esa es una buena pregunta. Intente registrar los valores del intento. 'Arrays.toString (yourAry [])' te ayudará aquí. –

+1

Como quería pasar una clase personalizada, me di cuenta de que solo tenía que implementar la interfaz de parcelable y que todo estaba bien. Gracias sin embargo. –

3

Otra posibilidad está utilizando intención.getAction:

En servicio:

public class SampleService inherits Service{ 
    static final String ACTION_START = "com.yourcompany.yourapp.SampleService.ACTION_START"; 
    static final String ACTION_DO_SOMETHING_1 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"; 
    static final String ACTION_DO_SOMETHING_2 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"; 
    static final String ACTION_STOP_SERVICE = "com.yourcompany.yourapp.SampleService.STOP_SERVICE"; 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     String action = intent.getAction(); 
     //System.out.println("ACTION: "+action); 
     switch (action){ 
      case ACTION_START: 
       startingService(intent.getIntExtra("valueStart",0)); 
       break; 
      case ACTION_DO_SOMETHING_1: 
       int value1,value2; 
       value1=intent.getIntExtra("value1",0); 
       value2=intent.getIntExtra("value2",0); 
       doSomething1(value1,value2); 
       break; 
      case ACTION_DO_SOMETHING_2: 
       value1=intent.getIntExtra("value1",0); 
       value2=intent.getIntExtra("value2",0); 
       doSomething2(value1,value2); 
       break; 
      case ACTION_STOP_SERVICE: 
       stopService(); 
       break; 
     } 
     return START_STICKY; 
    } 

    public void startingService(int value){ 
     //calling when start 
    } 

    public void doSomething1(int value1, int value2){ 
     //... 
    } 

    public void doSomething2(int value1, int value2){ 
     //... 
    } 

    public void stopService(){ 
     //...destroy/release objects 
     stopself(); 
    } 
} 

En Actividad:

public void startService(int value){ 
    Intent myIntent = new Intent(SampleService.ACTION_START); 
    myIntent.putExtra("valueStart",value); 
    startService(myIntent); 
} 

public void serviceDoSomething1(int value1, int value2){ 
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_1); 
    myIntent.putExtra("value1",value1); 
    myIntent.putExtra("value2",value2); 
    startService(myIntent); 
} 

public void serviceDoSomething2(int value1, int value2){ 
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_2); 
    myIntent.putExtra("value1",value1); 
    myIntent.putExtra("value2",value2); 
    startService(myIntent); 
} 

public void endService(){ 
    Intent myIntent = new Intent(SampleService.STOP_SERVICE); 
    startService(myIntent); 
} 

Por último, en el archivo de manifiesto:

<service android:name=".SampleService"> 
    <intent-filter> 
     <action android:name="com.yourcompany.yourapp.SampleService.ACTION_START"/> 
     <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"/> 
     <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"/> 
     <action android:name="com.yourcompany.yourapp.SampleService.STOP_SERVICE"/> 
    </intent-filter> 
</service> 
+0

Está comenzando el servicio varias veces ... ¿eso significa que se crearán múltiples instancias del mismo servicio cada vez? – oshurmamadov

+2

Los servicios tienen un patrón singleton. http://stackoverflow.com/questions/2518238/does-startservice-create-a-new-service-instance-or-using-the-existing-one –

+0

acción "cambiar (acción)" puede ser nula –

1

Actividad:

int number = 5; 
Intent i = new Intent(this, MyService.class); 
i.putExtra("MyNumber", number); 
startService(i); 

Servicio:

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    if (intent != null && intent.getExtras() != null){ 
     int number = intent.getIntExtra("MyNumber", 0); 
    } 
} 
0

Servicio: StartService puede causar efectos secundarios, la mejor manera de utilizar el mensajero y transmitir datos.

private CallBackHandler mServiceHandler= new CallBackHandler(this); 
private Messenger mServiceMessenger=null; 
//flag with which the activity sends the data to service 
private static final int DO_SOMETHING=1; 

private static class CallBackHandler extends android.os.Handler { 

private final WeakReference<Service> mService; 

public CallBackHandler(Service service) { 
    mService= new WeakReference<Service>(service); 
} 

public void handleMessage(Message msg) { 
    //Log.d("CallBackHandler","Msg::"+msg); 
    if(DO_SOMETHING==msg.arg1) 
    mSoftKeyService.get().dosomthing() 
} 
} 

Actividad: Obtener Messenger desde Intención llenarlo pasar los datos y pasar el mensaje al servicio de

private Messenger mServiceMessenger; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
mServiceMessenger = (Messenger)extras.getParcelable("myHandler"); 
} 


private void sendDatatoService(String data){ 
Intent serviceIntent= new 
Intent(BaseActivity.this,Service.class); 
Message msg = Message.obtain(); 
msg.obj =data; 
msg.arg1=Service.DO_SOMETHING; 
mServiceMessenger.send(msg); 
} 
Cuestiones relacionadas