【问题标题】:Android: Activity onResumeAndroid:活动 onResume
【发布时间】:2013-04-19 21:58:14
【问题描述】:

我有两个活动,家庭作业和接近。我的作业中有一首歌正在播放,但是当按下按钮时,媒体播放器会暂停并打开关闭。在我的 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);

        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();
    }


}

【问题讨论】:

  • 您是否在日志中遇到任何错误?

标签: android android-activity android-mediaplayer onresume


【解决方案1】:

尝试在活动的onPause() 方法中保存媒体状态,而不是在onClick()event 中。这保证了每次调用onResume() 时,都会在此之前调用onPause()(除非第一次运行活动,在这种情况下,onResume() 将在onStart() 之后调用。

【讨论】:

    【解决方案2】:

    如果 mediaplayer 为空,您为什么不尝试签入onResume()

    如果它为空,那么您需要调用mediaPlayer.prepare()

    也许把这段代码放到它自己的函数中:

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

    这样您就可以在onResume()/onCreate() 中调用它。在onResume() 中尝试进行空检查。如果它为空,则调用您的新函数来准备 mediaPlayer。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多