简体   繁体   中英

How to active a Foreground Service using a Mediaplayer Singleton

I am very newer in Android and I have a Mediaplayer Singleton because I am using fragment that show a list, I want that when the Mediaplayer Singleton is playing will active a service, I was trying with runOnUiThread but this only active many times the service.

this is the Singleton in MyMediaSingleton.java

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;
}

}

Thank you for your patience.

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;
    } 
    } 

Activity class

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();

} 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM