2

I just can't get what's wrong here.

Activity.java:

...
Intent intent = new Intent(Activity.this, Service.class);
intent.putExtra(Service.KEY_TEST, "123456789");
startService(intent);
...

Service.java:

...
private Intent intent;
public static final String KEY_TEST;

@Override
public void onCreate() {
    super.onCreate();
    Log.d("TEST", intent.getStringExtra(KEY_TEST)); // when I remove this line,
    // it works, otherwise gives NullPointerException and FC's
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.intent = intent;
    return START_STICKY;
}
...

The Service clearly doesn't receive the extras sent from the Activity. When I try to get any extras I sent before, the app force closes and LogCat gives NullPointerException. When I remove the line where I try to get the extras, the app doesn't force close, but I don't obviously receive the extras either.

Iiro Krankka
  • 4,959
  • 5
  • 38
  • 42
  • what errors do you get? What happens? What doesnt happen? Its hard to tell what you want with the question. – Jan Dragsbaek Nov 18 '11 at 12:31
  • Read the title of my question and my comment in the code. The line `Log.d...` force closes the app. LogCat is whining about NullPointerException, so the extras are not received. When I remove the line there's no force close but I obviously don't receive my extras either. – Iiro Krankka Nov 18 '11 at 12:34
  • You should write it specifically in your question, not in the title or in the code block. – Jan Dragsbaek Nov 18 '11 at 12:35
  • I thought everybody was supposed to read the title and contents of questions here. I'll edit the question. – Iiro Krankka Nov 18 '11 at 12:37

2 Answers2

5

put this line Log.d("TEST", intent.getStringExtra(KEY_TEST)); in,

onStartCommand(Intent intent, int flags, int startId) method..

EDIT:

For more info how the service life cyclces follows, Look at this Service Lifecycle.

user370305
  • 108,599
  • 23
  • 164
  • 151
  • I can't believe I made such a noob move. I guess that's what happens after 3 hours of non-stop coding. Works like a charm. – Iiro Krankka Nov 18 '11 at 12:41
  • There was the 3 minute time limit before I could accept your question. Why doesn't receiving extras work in onCreate in my case? – Iiro Krankka Nov 18 '11 at 12:49
  • Because your intent is received by service in onStartCommand() method, not in onCreate() that's why. Happy Coding.. :-) – user370305 Nov 18 '11 at 12:52
  • onStartCommand still gets fired before onCreate, right? I'm confused why I can't set the intent variable in onStartCommand and use it in onCreate. – Iiro Krankka Nov 18 '11 at 12:55
  • 1
    look at the link I provided in answer. You will get better understanding on how service works. – user370305 Nov 18 '11 at 13:01
0

onStartCommand() happens after onCreate() method.

Hexise
  • 1,520
  • 15
  • 20