RWillamy
RWillamy

Reputation: 53

how to change an imageView when a sound ends with threads

I need to change an ImageView when a sound ends , but when I try to use a thread to use it whitout to freeze the screem the application closes;

mp = MediaPlayer.create(this, R.raw.ave_maria);
    mp.start();
    im = (ImageView) findViewById(R.id.imag1);

    Thread thread = new Thread() {
        public void run() {

            while (mp.isPlaying()) {

            }
            im.setImageResource(R.drawable.primeiro_misterio_gozoso07);
        }
    };
    thread.start();

Upvotes: 4

Views: 104

Answers (4)

FoamyGuy
FoamyGuy

Reputation: 46856

You cannot change the UI from a background thread. Also MediaPlayer provides an OnCompletionListener interface which you should probably be using instead of a while loop. Infact if you utilize the onCompletionListener you wouldn't even have to put this on its own thread so you would not have to worry about how to change the UI.

something like this should work fine:

mp.setOnCompletionListner(new OnCompletionListner() {
    public void onCompletion(MediaPlayer m){
        im.setImageResource(R.drawable.primeiro_misterio_gozoso07);
    }
});

Upvotes: 1

Marcin S.
Marcin S.

Reputation: 11191

Use OnCompletionListener on mp object:

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

            // SET THE BACKGROUND HERE
            }
        }); 

Upvotes: 4

Milos Cuculovic
Milos Cuculovic

Reputation: 20223

You can use AsyncTask, it's a very useful class from Android and gives you the possibility to override 3 methods (onPreExecute, doInBackground and onPostExecute).

You could use doInBackground during the sound playing and onPostExecute to set your image.

Even better, you can use onPreExecute to display some nice things lake a progress dialog or something similar.

For the AsyncTask, please see: http://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 0

dougcunha
dougcunha

Reputation: 1238

You should to syncronize the code with thread UI.

mp = MediaPlayer.create(this, R.raw.ave_maria);
    mp.start();
    im = (ImageView) findViewById(R.id.imag1);

    Thread thread = new Thread() {
        public void run() {

            while (mp.isPlaying()) {

            }
            //YouActivity 
            YouActivity.this.runOnUiThread(new Runnable() {

            public void run() {
               im.setImageResource(R.drawable.primeiro_misterio_gozoso07);

            }
    });

        }
    };
    thread.start();

Upvotes: 2

Related Questions