Android Media Player Plays In The Background, But Doesn't Stop When App Killed

后端 未结 10 2052
被撕碎了的回忆
被撕碎了的回忆 2021-01-17 08:15

I\'m new to Android, so I have a problem. In Android I want to play background music as soon as my music player starts and have it continue even if the activity changes from

10条回答
  •  清歌不尽
    2021-01-17 08:51

    i did this by following way

    initialize

        MediaPlayer player;
        Music music;
    

    in OnCreate

        music = new Music();
        music.execute("abc");
    

    when you want to stop music, usually in onDestroy method

            music.cancel(true);
            if(player.isPlaying()){
            player.stop();
            player.release();
            }
    

    create music class

      public class Music extends AsyncTask
    {
    
        @Override
        protected Void doInBackground(String... params) {
    
            if(running)
            {
            player = MediaPlayer.create(getApplicationContext(), R.raw.bg_music1); 
            player.setVolume(100,100); 
            player.setLooping(true); 
            player.start(); 
            }
            else
            {
                player.stop();
                player.release();
            }
            return null;
        }
    
        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            super.onCancelled();
            running = false;
        }
    }
    

    another way is to use service

提交回复
热议问题