简体   繁体   中英

How to play music even if the app closes?

I am creating a media player in android studio and wants to play the music continue after the app closes. Code of service class is below:

public class myBackgroundService extends Service {
MediaPlayer mediaPlayer;
public myBackgroundService() {
}



@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public boolean onUnbind(Intent intent) {
    return super.onUnbind(intent);
}

@Override
public void onCreate() {
     mediaPlayer=MediaPlayer.create(this, R.raw.rockstar_marimba);
    mediaPlayer.setLooping(true);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    int a = 1;


    final String title = intent.getStringExtra("status");

    mediaPlayer.start();
          }

This code stop the music during closing the app.

Override some method in service onStop and onDestroy and call On destroy like below

public void onStop() {

    }
    @Override
    public void onDestroy() {
        mediaPlayer.stop();
        mediaPlayer.release();
    }

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