Search code examples
androidservicedatagramforceclose

Using Datagram in a Service in Android


I am trying to write an Android application which receives a Datagram packet and plays that packet (audio packet).

I want to use a Service for this purpose so there is not interruption in the audio. For this I have a service like this:

public class MyService extends Service {
  ... 
  AudioTrack track;
  DatagramSocket sock;
  DatagramPacket pack;
  ...

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    ...
    track = new AudioTrack(...)
    track.play();
    sock = new DatagramSocket(AUDIO_PORT);
    pack = new DatagramPacket(...)
    ...
    }

  @Override
  public void onStart(Intent intent, int startid) {
    ...
    while(true)
    {
        try {
            sock.receive(pack);
        } catch (IOException e) {
            e.printStackTrace();
        }
        track.write(pack.getData(), 0, pack.getLength());
    }
  }
 }

In my main activity I have a "START" button which when it is pressed it runs:

startService(new Intent(this, MyService.class));

The app works fine and plays the received audio well, however after pressing the start button:

  1. It does not respond to any other button

  2. After a while I get this message: "Application MyAppName is not responding" and it gives two options Forceclose and Wait. If I press Wait the audo continues to play nicely but the UI is not responding anymore.

To me it looks like putting while(true) in the onStart may have caused this.

Any help and pointer in doing this in a correct way is appreciated.


Solution

  • Here's an example:

    public void onStart(Intent intent, int startid) {
        ...
        Thread streamer = new Thread() {
    
            @Override
            public void run() {
                while(true) {
                    try {
                        sock.receive(pack);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    track.write(pack.getData(), 0, pack.getLength());
                }
            }
        });
        streamer.setPriority( Thread.MAX_PRIORITY );
        streamer.start();
      }
    

    Obviously, in the final version of your code, you will want to keep track of the Thread you create so that you can check its status or terminate it, and/or create a Handler in the thread so that you can control it from the service.