Android - Starting a service with extra information through put/getExtra
Asked Answered
M

2

12

I've really tried to get through the intent.putExtra() and getIntent().getExtras() and apply them to one of the SimpleService tutorials. I know a lot of people have already asked "why is bundle extras always null?" I promise I tried to hack through the answers I found here for several hours before I considered posting but I don't think I'm advanced enough to really understand what it is I must be doing wrong with the minor snippets people are posting. As such I put in the full code of my activity and my service.

I think my issue is the that my starting intent (the one I create in my activity) doesn't exist in the context of my service. I wonder if maybe I'm using Intents in the wrong direction/purpose entirely? I did try an intent.putExtra in my service, to try to send a string the other direction, but those extras are always null, too. So at the risk of repetition, why is bundle extras always null? How do I make a single intent that exists both in the context of my activity and my service?

I should note that the code as displayed below obviously will have a null extras because I've commented out a few of my attempts to .getExtras() that have failed. I deleted the rest for the sake of cleanliness.

EDIT: The answer thanks to the replies, in code for the sake of those who have also been Googling for hours. Put this in your service (please note that the return START_REDELIVER_INTENT may be wrong):

@Override
public int onStartCommand( Intent intent , int flags , int startId )
{
      super.onStartCommand(intent, flags , startId);

      extras = intent.getExtras();

          //just checking
      if( extras != null )
      Toast.makeText(this,extras.getString("extratoservice"), Toast.LENGTH_SHORT).show();

      return START_REDELIVER_INTENT;

}

My activity (based on Sai Geetha's blog):

package com.example.BroadcastIntent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class BroadcastIntentActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button start = (Button)findViewById(R.id.buttonStart);
    start.setOnClickListener(startListener);

    Button stop = (Button)findViewById(R.id.buttonStop);
    stop.setOnClickListener(stopListener);   

    //the intent I'm using to start and stop the service -- the extras don't go anywhere....
    intent = new Intent(BroadcastIntentActivity.this,BroadcastService.class);     
    intent.putExtra("extratoservice", "if you can read this, it made it to the service" );

}

Boolean serviceRunning;
Intent intent;

//Clicks from Geetha's Blog
private OnClickListener startListener = new OnClickListener() {
     public void onClick(View v){

         startService(intent);
         serviceRunning = true;
     }                 
};

private OnClickListener stopListener = new OnClickListener() {
    public void onClick(View v){

         try
         {
             stopService(intent);
             serviceRunning = false;                
         }
         catch( Exception e)
         {
             Toast.makeText(getApplicationContext(), "Service was not running...",Toast.LENGTH_SHORT).show(); 
         }
     }                 
 };

}

And this is my service:

package com.example.BroadcastIntent;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

public class BroadcastService extends Service{

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub

    //extras = arg0.getExtras();    <-- this has null extras, too...

    return null;
}

Bundle extras;

@Override
public void onCreate() {
      super.onCreate();

      // extras = getIntent().getExtras();   <-- this is undefined?

      if( extras == null )
      Toast.makeText(this,"Service created... extras still null", Toast.LENGTH_SHORT).show();
      else
      Toast.makeText(this,extras.getString("extratoservice"), Toast.LENGTH_SHORT).show();

}

@Override
public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_SHORT).show();

}
}
Meow answered 13/11, 2011 at 15:51 Comment(3)
Welcome to Stackoverflow! If you find a response is helpful, please up vote it. If the response successfully answers your question, please click the green check mark next to it to accept the answer. Also please look at stackoverflow.com/questions/how-to-ask for advice on how to write a good questionTetanize
Kurtis, I like your stock invitation! I'm glad someone's taking the time to inform the new arrivals of how to use the service :)Alita
@Adam: I don't understand, sorry: your service code at the end does NOT have the onStartCommand()??Dwarfish
C
17

you need to look at the onStartCommand() function (I'm not at a desktop so I can't conveniently link to the javadoc). This will receive the intent you passed and your extras should be available there.

Camboose answered 13/11, 2011 at 16:0 Comment(3)
Nice - now to figure out how to send a message back.Meow
Thanks for the URL hookup @H9kDroid. As far as responding, you have a couple of options: either use a BroadcastReceiver or use onBind.Camboose
One possibly bad hack I've realized I can do - since my service is running in the same process (I think?) as my application, I can actually access/change any public variables that I would like to... it'd be a bad idea for running a service as a real service - but it works for my simple tutorial purposes.Meow
A
2

I think you need to do this in your service..

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

to get the intent you're passing in... but I'm not 100% on this, so double check http://developer.android.com/reference/android/app/Service.html

Alita answered 13/11, 2011 at 16:4 Comment(2)
It works, thanks. Incidentally, it seems I have to actually wait for onCommand() to happen after onCreate(). Then I'm able to receive the extras.Meow
From the documentation: This is the old onStart method that will be called on the pre-2.0 platform. On 2.0 or later we override onStartCommand() so this method will not be called.Manicurist

© 2022 - 2024 — McMap. All rights reserved.