Search code examples
androidandroid-activityandroid-mediaplayeronresume

Android: Activity onResume


I have two activities, homework and closer. I have a song playing in homework but when a button is pressed, the media player pauses and closer is opened. In my onResume function for homework, I'm trying to start the media player again but no sound plays. Can anybody help me out with this?

package com.cis.lab4;

import java.io.IOException;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Homework extends Activity {

    final MediaPlayer mediaplayer = new MediaPlayer();
    int media_length;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homework);

        setContentView(R.layout.activity_homework);
        AssetFileDescriptor afd;
        try {
            afd = getAssets().openFd("rev.mp3");
            mediaplayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            mediaplayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaplayer.start();
        Button next = (Button) findViewById(R.id.homeworkContinue);
        final Intent openCloser = new Intent(this, EndActivity.class);
        next.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                mediaplayer.pause();
                media_length = mediaplayer.getCurrentPosition();
                startActivity(openCloser);

            }

        });
    }

    public void onResume(Bundle savedInstanceState){
        super.onResume();
        mediaplayer.seekTo(media_length);
        mediaplayer.start();
    }


}

Solution

  • Try saving the media state in the onPause() method of the activity instead of instead of in the onClick()event. This guarantees that every time the onResume() will be called the onPause() will be called before that (except for the first time the activity runs, in which case the onResume() will be called after the onStart().