Search code examples
androidmedia-playeraudio

play the sound again when the user get back to activity


what i have is an activity which i play some sound each the user open it , but when he got to the child activity of it .. it stops as i want .. but i want the user when he press back button and return to this activity (which is parent activity) to play this sound again ... how can i do this .. here is some of my code:

 public class GeneralScreen extends Activity {
    String mytext="";
    MediaPlayer mMediaPlayer;
    protected static final int RESULT_SPEECH = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.general_screen);


        GridView g = (GridView) findViewById(R.id.myGrid);
         mMediaPlayer = new MediaPlayer();
        mMediaPlayer = MediaPlayer.create(this, R.raw.selecteng);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setLooping(false);
        mMediaPlayer.start();

        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            public void onCompletion(MediaPlayer mp) {

                Log.i("Completion Listener","Song Complete");
                Toast.makeText(GeneralScreen.this, "Media Completed", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  //for open google API
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");     //for transfer voice from google API to text in EditText

                try {
                    startActivityForResult(intent, RESULT_SPEECH);  // for get result


                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),   //if make error get this message
                            "Ops! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });

Solution

  • Just create a method playYourMusic() and put all the code to start mediaplayer inside. Then put the playYourMusic into onRestart and in onCreate():

        @Override
       protected void onRestart() {
    
        playYourMusic();
    
         super.onRestart();
    
    
       }
    

    Think on it, to finish the activity that You are leaving when You will go back to main. So, why not in onResume()? Because onResume() is also called at the start of Activity. Some devices handle the LifeCycle of android in a different way.