A
A
Artem2012-08-16 15:16:53
Java
Artem, 2012-08-16 15:16:53

How to synchronize method?

I have a task to synchronize a method. Tried with wait()/notify() and semaphores. As a result, the lock works as it should, but the onCompletion() method is not called and, as a result, the lock is not released. How to be?

Object lock = new Object();

    public void playSound(String path) {
        Uri myUri = Uri.parse(path);
        MediaPlayer mp = MediaPlayer.create(context, myUri);
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                mp.release();
                lock.notifyAll();
            }
        });
        mp.start();
        
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
LeoCcoder, 2012-08-16
@LeoCcoder

Documentation:
“In order to receive the respective callback associated with these listeners, applications are required to create MediaPlayer objects on a thread with its own Looper running”
If there are unfamiliar words in this sentence, I advise you to study everything, then it will be clear why it does not work.
Most likely lock.wait(); blocks the thread and messages are no longer processed, so you would not receive any more callbacks (if you have a Looper in the thread at all, show in which thread you create the player). If you do not have a Looper in the thread, then even without blocking, you will not get any callbacks back.

A
AR1ES, 2012-08-16
@AR1ES

Hmm, if we are talking about the synchronization of a method, then simply declaring it as synchronized is not appropriate?

A
Artem, 2012-08-16
@bartwell

If you do not have a Looper in the thread, then even without blocking, you will not receive any callbacks

Looper is and without blocking OnCompletionListener () works normally.
Most likely lock.wait(); blocks the thread and messages are no longer processed, so no more callbacks would be received

It looks very much like it. And how to fix it?

A
Artem, 2012-08-16
@bartwell

With a list Uri does not suit me: other methods can be called between sounds.
My task is that I need to track the end of playing the melody and only after that perform further actions. This method is called using Method.invoke(). Accordingly, you need to wait either inside the method or immediately after invoke (), there are no other options. But it's the same thread...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question