This kind of busy waiting is definitely not a good idea for handling this kind of situation. You might consider having an interface declared like this.
public interface MediaResponseListener {
void mediaResponseReceiver(String result);
}
Then you need to implement the interface
in your MainActivity
like this.
public class MainActivity extends Activity implements MediaResponseListener {
// Your onCreate and other function goes here
// Then you need to implement the function of your interface
@Override
public void mediaResponseReceiver(String result) {
// Do something with the result
}
}
Now you declare an interface
in your Service
class too and when you're starting the Service
from your MainActivity
pass the reference of the interface
. So your Service
may look like this.
public AudioService extends Service {
// Declare an interface
public MediaResponseListener mMediaResponseListener;
// ... Your code
// When some error occurs or you want to send some information to the launching Activity
mMediaResponseListener.mediaResponseReceiver(result);
}
And while starting the Service
from your Activity
you need to pass the reference of the interface
to the Service
. So in your MainActivity
you need to do something like this.
private AudioService mAudioService;
mAudioService. mMediaResponseListener = this;
startService();
Here's how you can avoid the busy waiting and can receive the response from the Service
time to time.
Now the behaviour can be achieved in many other ways, like you've already tried with local broadcast.
So why don't you just declare a BroadcastReceiver
in your Activity
which will be invoked when any Broadcast
is received from the Service
.
Here's a nice implementation of how you can send and receive broadcast.