Jason Mantra
Jason Mantra

Reputation: 105

Is it possible to wait in a while loop immediately after starting an android service?

Long story short, I'm starting a service and inside the service it initializes a static variable and I'm waiting in the main thread afterwards for this static variable to be set. So I tested it and it was stuck (as in forever in the while loop) and it's starting to make me think it's not possible. My logic is the service job gets put into the main thread queue to be executed but it hasn't started yet and it will only start until the current main thread job is done and the service job can only start after. So it seems impossible to me. Is this the correct logic? Below is the code.

Intent exampleIntent = new Intent(this, Example.class);
startService(exampleIntent);
while(Example.variable == null) {
  //waiting for it to be initialized
}

Upvotes: 0

Views: 108

Answers (2)

That code seems wrong :D

First you should use Service bounding to bound to the service and communicate with it. This way you know when the service is running and you can communicate with it. And second you should not wait in while loops for something to happen. Use some Observer pattern or LiveData or send an intent to the activity to make the server announce the activity it has finished it's work. Do not wait into the activity for the service to do it's work. Waiting in while loop will block the UI thread and the application will freeze

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006674

I'm starting a service and inside the service it initializes a static variable and I'm waiting in the main thread afterwards for this static variable to be set

That's not possible. The service will not be started until you return control of the main application thread back to the framework.

So, revise your approach to have your service let the activity know when its work is done by some other means, such as using an event bus (greenrobot's EventBus, LocalBroadcastManager, MutableLiveData, an Rx-based event bus, etc.).

Upvotes: 1

Related Questions