Search code examples
androidandroid-mediaplayer

using AsyncTask with mediaplayer in Android


i am developing an android application i have a function to play music from online streaming it take a time to make the application lunch up so i need to give the media player task to a thread to make the application lunch quickly and the thread take the media player so when i make this operation the application give me an exception that mediaplayer.prepare() need the main thread so i will post what i try in my code:

public void playsong()
{
            mediaplayer mp =new mediaplayer();
            String currentUrl = sora.getUrl(this);  
            mp.reset();
            mp.setDataSource(currentUrl);
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setOnBufferingUpdateListener(this);
            mp.prepare();
            mp.start();

}




public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.player);
        initView();
        thread.start();

         }


Thread thread = new Thread()
{
    @Override
    public void run() {
        try {
          playSong();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
    }
};

Solution

  • For that you have to use AsyncTask...

    class PalyMusic extends AsyncTask<Void, Void, Void> {
    
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
    
        }
    
        @Override
        protected Void doInBackground(Void... unused) {
    
    
          //your background process
    
    
            return (null);
        }
    
        protected void onPostExecute(Void unused) {
    
            //here you can call your mp.prepare();
        }
    
    }
    

    and for calling this

       new PalyMusic().execute();
    

    Don't forget to add this to AndroidManifest.xml file:

    <uses-permission android:name="android.permission.INTERNET"/>