Search code examples
androidmedia-player

Android MediaPlayer


I want to prepare my mediaplayer on this activity and when its prepared I want to jump to another activity and start the mediaplayer there. It doesn't jump to the other activity can you help me please?

        public void run() {

            try {
                mp.setDataSource(urls.getFirst());
                mp.setAudioStreamType(AudioManager.STREAM_MUSIC);       
                mp.setOnPreparedListener(new OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        Intent i = new Intent(Start.this, RadyoBabylonActivity.class);
                        startActivity(i);
                    }
                });
                mp.prepare();   

            } catch (Exception e) {

                e.printStackTrace();
            }   
        }
    });
    th.start();

Solution

  • I believe the issue here is that you are trying to start an Activity directly from a background thread. I do not believe this is possible to do directly in Android - instead you must have the Activity start from the UI thread. Therefore, the way to do this in Android is to use a Handler. The Handler lives on the UI thread and receives messages from the background thread to do your UI actions such as starting another Activity.

    Example:

    //Inside your activity:
    final Handler messageHandler = new Handler() {
        public void handleMessage(Message msg) 
        {
            //Start Activity
            Intent i = new Intent(Start.this, RadyoBabylonActivity.class);
            startActivity(i);
        }
    }
    
    //Inside onPrepared(MediaPlayer mp):
    messageHandler.sendEmptyMessage(0);
    

    See also: http://developer.android.com/reference/android/os/Handler.html