Search code examples
androidmultithreadingstreamingshoutcast

How to apply threading while streaming a URL.?


I have a code to play an online radio on shoutcast server. When the app is launched, it streams the file and plays it. Now the problem is that if I have no network connection or improper network connection, the status of the app remains in "Streaming" mode forever. I want to add a thread with this streaming thing which should wait for 20 seconds, and if it is not able to connect to the server, it should throw an event to exit the app stating "improper network connection". Or if there is any other idea to that, it will be appreciated as well.. The code to play the media is,

public void playFm() {
    Uri myUri = Uri.parse("http://108.166.161.206:8826/;stream.mp3");
    try
    {
        if (mp == null) {
            this.mp = new MediaPlayer();
        } else {
            mp.stop();
            mp.reset();
        }
        mp.setDataSource(this, myUri); // Go to Initialized state
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        streaming=true;
        progress.setVisibility(View.VISIBLE);
        stream.setVisibility(View.VISIBLE);
        stop.setEnabled(false);
        mp.setOnPreparedListener(this);
        mp.setOnBufferingUpdateListener(this);

        mp.setOnErrorListener(this);
        mp.prepareAsync();
        Log.d(TAG, "LoadClip Done");
    } catch (Throwable t) {
        Log.d(TAG, t.toString());
    }
}

Thanx to all in advance..


Solution

  • Here is the answer..

      iRunnable=new Runnable() 
                {
    
                            @Override
                            public void run() 
                            {
                                //do something
                             }
                        };
    

    and in the other function

     Thread th = new Thread() {
            @Override
            public void run() {
    
                    try {
                        Thread.sleep(1000*15);
                        //your code here..
                        iHandler.postDelayed(iRunnable,20*1000);
                    } 
    catch (InterruptedException ie) 
              {
    
              }
        };
        th.start();
        }