如何使用Mediaplayer Singleton激活前台服务

时间:2017-04-30 01:08:28

标签: java android

我在Android中比较新,我有一个Mediaplayer Singleton因为我正在使用显示列表的片段,我希望当Mediaplayer Singleton正在播放时会激活一个服务,我尝试使用runOnUiThread但这只是多次激活服务。

这是MyMediaSingleton.java中的Singleton

public class MyMediaSingleton {
MediaPlayer player;
private static volatile MyMediaSingleton instance=null;
private MyMediaSingleton(){

}

public static MyMediaSingleton getInstance(){

    if(instance==null){
        synchronized (MyMediaSingleton.class){
            if(instance==null){
                instance=new MyMediaSingleton();
            }
        }
    }

    return instance;
}

}

感谢您的耐心等待。

1 个答案:

答案 0 :(得分:0)

Media Player Singleton Class

public class MyMediaSingleton  { 
    MediaPlayer mp;
    private static volatile MyMediaSingleton  instance = null;
    private MyMediaSingleton () { } 

    public static MyMediaSingleton  getInstance() { 
        if (instance == null) {
            synchronized (MyMediaSingleton .class) { 
                if (instance == null) {
                    instance = new MyMediaSingleton ();
                } 
            } 
        } 

        return instance;
    } 
    } 

活动类

public class MainActivity extends Activity {

private MyMediaSingleton player = getInstance();

@Override 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

} 

public void playSound(View view){
    if(player.mp==null) 
      player.mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
      player.mp.start(); 

    //For playing multiple sound using single MediaPlayer do it as:
    if(player.mp ==null) 
  player.mp = new MediaPlayer(); 
else 
  player.mp.reset(); 
String fileName="android.resource://"+getPackageName()+
                                               "/"+ R.raw.sound;
player.mp.setDataSource(getApplicationContext(),Uri.parse(fileName));
player.mp.prepare(); 
player.mp.start();

} 
}