我正在使用Android媒体播放器类在我的Android应用程序中播放通知声音。
MediaPlayer player = MediaPlayer.create(getApplicationContext(), R.raw.notify);
player.setLooping(false);
player.start();
我需要在不同的活动中播放不同的通知声音,所以每次我需要播放声音时我需要创建媒体播放器实例然后我需要说开始。
但是,不是这样做,我如何在整个应用程序中维护媒体播放器的单个实例,并在所有活动中使用它来播放声音。
有人可以建议我更好的实施方法。 从我的角度来看,我将创建一个单例类,我将在此类中添加所有与MediaPlayer相关的函数。
感谢。
答案 0 :(得分:15)
您应该考虑 Singleton pattern 。创建一个具有静态方法getMediaPlayer()
的MyPlayer类,每次调用时返回相同的MediaPlayer实例。
答案 1 :(得分:4)
我总是用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);
}
与经典单身人士相比,你可以定义单身人士的范围。有时您只需要将实例保留在同一个Activity中,但第二个Activity可能具有不同的实例。如果您需要跨不同的Activity,则只需传递context.getApplicationContext()。
答案 2 :(得分:1)
注意:此处,连续创建一系列玩家(比如20个mediaPlayers)时Audioservice失败的问题也得到了解决。
创建播放器:单例类应该创建另一个线程来处理媒体播放器操作(而不是主UI线程)
创建Player Runnable :此线程(由单例实例创建的应该被赋予后台优先级,延迟为&#34; Thread.sleep(500);&#34;在创建逻辑之前允许MediaPlayer.create()使用的AudioService完成其工作,因为后面的方法立即返回。
创建播放器可运行代码:
/**
* 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's interrupt flag
Thread.interrupted();
}
}
}