androidandroid-activityandroid-asynctask

onPause() and onStop() not working


public class PhrasesActivity extends AppCompatActivity {
    MediaPlayer mediaPlayer;
    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener(){
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            releaseMediaPlayer();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.word_list);

        final ArrayList<Word> words = new ArrayList<Word>();

#some Word elements added
        WordAdapter wordAdapter = new WordAdapter(this, words, R.color.category_phrases);
        ListView listView = (ListView)findViewById(R.id.numberlist);
        listView.setAdapter(wordAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(PhrasesActivity.this, "Demo", Toast.LENGTH_SHORT).show();
                Word word = words.get(i);
                releaseMediaPlayer();
                mediaPlayer = MediaPlayer.create(PhrasesActivity.this, word.getAudioResourceID());
                mediaPlayer.start();
                mediaPlayer.setOnCompletionListener(onCompletionListener);
            }
        });
    }

@Override
protected void onPause() {
    super.onPause();
    Log.v("PhrasesActivity", "onPause: Paused");
    releaseMediaPlayer();
}

@Override
protected void onStop() {
    super.onStop();
    Log.v("PhrasesActivity", "onPause: Stopped");
    releaseMediaPlayer();
}

    private void releaseMediaPlayer(){
        if(mediaPlayer!= null){
            mediaPlayer.release();
            mediaPlayer= null;
        }
    }
}

This code isn't working in child-activity in my app. I have tried checking logs with Log.v() but, nothing is happening at all. No log is created. EDIT -I tried using onPause() method only. That also didn't helped me solve the problem.


Solution

  • Error in the code is in the sequence of using required instruction statements before calling super.onStop()/super.onPause();

    @Override
    protected void onPause() {
        // super.onPause();
        Log.v("PhrasesActivity", "onPause: Paused");
        releaseMediaPlayer();
        super.onPause();
    }
    
    @Override
    protected void onStop() {
        // super.onStop();
        Log.v("PhrasesActivity", "onPause: Stopped");
        releaseMediaPlayer();
        super.onStop();
    }
    

    Generally, in java we first call super(); in overridden method and then proceed for further code writing. I didn't get why it is not followed here, but changing code as above helped me solve the problem.

    Thanks to Mohammed Atif for help!