Search code examples
androidandroid-mediaplayer

stop mediaplayer if going back to activity but keep it playing if user go to home screen


Hello i have first activity to choose music from list and when i choose it , the music player opens as second activity so what i need is when going back to home screen in phone so the music keep playing in the background but if the user press the backarrow on the actionbar so the music stops and move back to first activity (music list) so how can i handle these things please ? can you provide me with code ```

@Override
    public void onBackPressed() {
        Intent mainActivity = new Intent(Intent.ACTION_MAIN);
        mainActivity.addCategory(Intent.CATEGORY_HOME);
        mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(mainActivity);
        //need to keep music playing
    }

    void gobacktopreviousactivity(){

       //stop music player
    }

Solution

  • @Override
        public void onBackPressed() {
            Intent mainActivity = new Intent(Intent.ACTION_MAIN);
            mainActivity.addCategory(Intent.CATEGORY_HOME);
            mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(mainActivity);
            //keep music playing
        }
    
        void gobacktopreviousactivity(){
            //stop music player
            mediaPlayer.stop();
            mediaPlayer.release();
        }