Play background music in all activities of Android app

后端 未结 5 914
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 01:03

I spend about 20 hours until now and my problem there still is . I am creating an android application that has several Activities (mainMenu , aboutUs,setting). I followed th

5条回答
  •  攒了一身酷
    2020-12-07 01:53

    You could put the music player in a service. This would make it independent from the Activities and you would still be able to control the playback through intents.

    Here are some code example about it: https://stackoverflow.com/a/8209975/2804473 The code below is written by Synxmax here at StackOverflow, and covered in the link above:

    public class BackgroundSoundService extends Service {
        private static final String TAG = null;
        MediaPlayer player;
        public IBinder onBind(Intent arg0) {
    
            return null;
        }
        @Override
        public void onCreate() {
            super.onCreate();
            player = MediaPlayer.create(this, R.raw.idil);
            player.setLooping(true); // Set looping
            player.setVolume(100,100);
    
        }
        public int onStartCommand(Intent intent, int flags, int startId) {
            player.start();
            return 1;
        }
    
        public void onStart(Intent intent, int startId) {
            // TO DO
        }
        public IBinder onUnBind(Intent arg0) {
            // TO DO Auto-generated method
            return null;
        }
    
        public void onStop() {
    
        }
        public void onPause() {
    
        }
        @Override
        public void onDestroy() {
            player.stop();
            player.release();
        }
    
        @Override
        public void onLowMemory() {
    
        }
    }
    

提交回复
热议问题