Android: onResume/onPause 和 mediaplayer

标签 android scope media-player onresume onpause

我有两项 Activity ,家庭作业和闭门作业。我在作业中播放了一首歌曲,但是当按下按钮时,媒体播放器暂停并关闭了。在我的 onPause 函数中,我试图暂停媒体播放器,但它不起作用, Activity 打开得越近,音乐仍在播放。之前,我设置了它,以便在 Activity 作业的按钮监听器中,媒体播放器暂停,但当我在 onResume 中设置它时,媒体播放器不会恢复。我认为这可能是媒体播放器的范围问题,有人可以帮我解决这个问题吗?

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);
        setPlayer();
        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) {
                startActivity(openCloser);

            }

        });
    }

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

    public void onPause(Bundle savedInstanceState){
        mediaplayer.pause();
        media_length = mediaplayer.getCurrentPosition();
    }


    public void setPlayer(){
        AssetFileDescriptor afd;
        try {
            afd = getAssets().openFd("rev.mp3");
            mediaplayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            mediaplayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

最佳答案

你没有正确覆盖 onPause。

请试试这个 onPause isstead:

    @Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();

    mediaplayer.pause();
    media_length = mediaplayer.getCurrentPosition();
}

那应该没问题。你应该对 onResume 做同样的事情。 晚安。

关于Android: onResume/onPause 和 mediaplayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16157362/

相关文章:

binding - AngularJS如何绑定(bind) map

JavaScript 告诉哪个条件被击中

java - 如何在Android中使用媒体播放器?

azure - 使用 Azure Media Player 按需查看 Azure 存储中的 MP4 文件

android - 为什么我的if语句只运行android中的else部分

android - 从联系人应用程序中选择联系人;但仅列出带有电子邮件的联系人

javascript - AngularJS 嵌套作用域和更改 $parent 作用域变量

android - 当应用程序有加载时间时如何最大化用户体验

android - 以编程方式为应用程序设置自定义通知铃声(从移动设备中的音频文件中选择)

android - Android 包安装期间写入元信息