在所有活动中使用一个公共媒体播放器类 [英] One public media player class to be used across all activities
问题描述
已更新.
在提出建议之后,我决定在新线程中运行媒体播放器.因为我仅在屏幕上显示活动时才需要Media Player.这是新代码:
After the recommendations, I decided to run media player in a new thread. Because I need Media Player only when activities are on the screen. Here is the new code:
首先,在多个类中使用了我的公共SingleMP(媒体播放器)类:
First, my public SingleMP (Media Player) class used in multiple classes:
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
public class SingleMP implements Runnable
{
public static MediaPlayer mp;
private static Context context;
private static Uri uri;
public SingleMP(Context context, Uri uri){
this.context= context;
this.uri= uri;
}
@Override
public void run(){
try {
if (mp != null) {
mp.stop();
mp.reset();
mp.release();
mp = null;
}
mp = MediaPlayer.create(context, uri);
mp.start();
} catch (Exception e) {
if (mp != null) {
mp.stop();
mp.reset();
mp.release();
mp = null;
}
e.printStackTrace();
mp = MediaPlayer.create(context, uri);
mp.start();
}
}
// Called in OnDestroy of used class.
public static void mpstop()
{
if (mp != null) {
mp.stop();
mp.reset();
mp.release();
mp = null;
}
}
}
以及在另一个Java类中使用它的示例:
And an example of using it in another Java class:
public class MainMenu
{
private Uri uri;
private Runnable MPthread;
public void onCreate(Bundle savedInstanceState)
{
RadioButton rbtnA = (RadioButton) findViewById(R.id.radio0);
rbtnA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
// Assign a sound from raw folder.
uri =Uri.parse("android.resource://"+getPackageName()+"/raw/nice");
MPthread = new SingleMP(MainMenu.this, uri));
new Thread(MPthread).start();
}
}
});
RadioButton rbtnB = (RadioButton) findViewById(R.id.radio1);
rbtnB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
// Assign a sound from raw folder.
uri =Uri.parse("android.resource://"+getPackageName()+"/raw/morning");
MPthread = new SingleMP(MainMenu.this, uri));
new Thread(MPthread).start();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if(MPthread!=null) {
SingleMP.mpstop();
}
}
}
您怎么看?看来我的用户界面工作起来更流畅了.
What do you think? It seems that my UI works a little bit smoother.
推荐答案
您的媒体播放器实例将驻留在主线程(即UI线程)上.不建议这样做.
Your media player instance is going to live on the main thread, which is the UI thread. This is not recommended.
我可能会创建一个服务,该服务将创建一个包含媒体播放器的新线程.然后,您的每个活动都可以绑定到该服务以控制媒体播放器.
I would probably create a service that would create a new thread holding the media player. Each of your activities could then bind to the service to control the media player.
请参见扩展服务类.
您还可以查看媒体播放器示例.
这篇关于在所有活动中使用一个公共媒体播放器类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!