How to support a single instance of MediaPlayer [Android]

I am using the Android media player class to play notification sounds in an Android application.

MediaPlayer player = MediaPlayer.create(getApplicationContext(), R.raw.notify);
player.setLooping(false);
player.start();

I need to play different notification sounds in different actions, so every time I need to play a sound, I need to create an instance of the media player, and then I need to say the beginning.

But instead, how can I maintain a single copy of the media player throughout the application and use it in all actions to play sounds.

Can someone please suggest me the best way to implement it. From my point of view, I will create one singleton class, and I will add all the MediaPlayer related functions in this class.

Thank.

+5
source share
3

Singleton. MyPlayer getMediaPlayer(), MediaPlayer.

+15

Singleton Pattern. Android, :

public class Asset{
     public static Asset(Context context);
}

, :

private static Hashtable<Context, Asset> instances;

public static Asset(Context context){
    if (!instances.containKey(context)){
        instances.put(context, new Asset(context));

    return instances.get(context);
}

, . , , . , context.getApplicationContext().

+4

:

: Audioservice (, 20 mediaPlayers) .

: singleton ( )

Create a Runnable Player . This thread (created by a singleton instance must have background priority, a delay of “Thread.sleep (500);” before creating the logic to allow AudioService, MediaPlayer.create () to complete its work, since the method later returns instantly.

Create an executable player code :

/**
 * Created by George hannuneh on 10/12/2015.
 * Holds the background work for creating a media player
 */
public class CreatePlayerRunnable implements Runnable {

static final int CREATE_STATE_FAILED = -1;
static final int CREATE_STATE_STARTED= 0;
static final int CREATE_STATE_COMPLETED= 1;
private static final String TAG ="CreatePlayerRunnable";
private static int sRunnablesCount = 1;


final TaskRunnableCreatePlayerMethods mPlayerTask;

/**
 *
 * An interface that defines methods that PlayerCreationTask implements. An instance of
 * CreatePlayerTask passes itself to an CreatePlayerRunnable instance through the
 * CreatePlayerRunnable constructor, after which the two instances can access each other's
 * variables.
 */
interface TaskRunnableCreatePlayerMethods {
    /**
     * Sets the Thread that this instance is running on
     * @param currentThread the current Thread
     */
    void setCreatePlayerThread(Thread currentThread);

    Context getActivity();

    Uri getMediaUri();

    void handleCreationState(int createStateFailed);

    void setPlayer(MediaPlayer returnMediaPlayer);

    String getPlayerId();

    MediaPlayer getPlayer();
}
/**
 * This constructor creates an instance of CreatePlayerRunnable and stores in it a reference
 * to the CreatePlayerTask instance that instantiated it.
 *
 * @param createPlayerTask The CreatePlayerTask
 */
CreatePlayerRunnable(TaskRunnableCreatePlayerMethods createPlayerTask) {
    mPlayerTask = createPlayerTask;
}
@Override
public void run() {
    /*
     * Stores the current Thread in the CreatePlayerTask instance,
     * so that the instance
     * can interrupt the Thread.
     */
    mPlayerTask.setCreatePlayerThread(Thread.currentThread());
    // Moves the current Thread into the background
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
    MediaPlayer returnMediaPlayer = null;

    try {

        Thread.sleep(500);
        // Before continuing, checks to see that the Thread hasn't
        // been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        returnMediaPlayer = MediaPlayer.create(mPlayerTask.getActivity(), mPlayerTask.getMediaUri());
        if (returnMediaPlayer == null) {
            Log.e("CreatePlayerRunnable", mPlayerTask.getMediaUri()+ " - failed to create player");
            return;
        }
        PlayerEventsHandler playerEvents = new PlayerEventsHandler(mPlayerTask.getPlayerId());
        returnMediaPlayer.setLooping(true);
        returnMediaPlayer.setOnCompletionListener(playerEvents);
        returnMediaPlayer.setOnErrorListener(playerEvents);
        returnMediaPlayer.setVolume(0f, 0f);
        returnMediaPlayer.start();
    } catch (InterruptedException e1) {
        // Does nothing
    } catch(Exception e)
    {
        returnMediaPlayer = null;
        e.printStackTrace();
    }
    finally {
        if(MainActivity.DEBUG_MODE_ENABLED){
            Log.d(TAG, "end of runnable: "+ sRunnablesCount++);
        }
        if (null == returnMediaPlayer){
            mPlayerTask.handleCreationState(CREATE_STATE_FAILED);
        } else {
            mPlayerTask.setPlayer(returnMediaPlayer);
            // Reports a status of "completed"
            mPlayerTask.handleCreationState(CREATE_STATE_COMPLETED);
        }

        // Sets the current Thread to null, releasing its storage
        mPlayerTask.setCreatePlayerThread(null);
        // Clears the Thread interrupt flag
        Thread.interrupted();
    }

}

}

+1
source

All Articles