0

I have an app that streams audio. In a separate thread I call my service to start while displaying a progress dialog to the user. The Service will either start the audio or have an error within 10 or so seconds. The hacky way I have it now is that when the Service has determined that the audio is either prepped and ready or an error, it sends a local broadcast message back to my Activity with that info. This signals my main activity that the service is done loading and prepping the media and I can dismiss the progress dialog, etc.

Right now I have the MainActivity just waiting in a do while loop, displaying a progress dialog, checking a variable until it receives the broadcast from the service which changes said variable

I know that this is probably not the right way to do this so my question is, what is the proper way to do this? Thanks.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
ShadowGod
  • 7,891
  • 3
  • 28
  • 31
  • 1
    Get rid of the loop. The `ProgressDialog` should be sufficient. Just dismiss it when the broadcast is received. – Mike M. Oct 01 '16 at 06:01

1 Answers1

0

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.

Community
  • 1
  • 1
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98