当屏幕锁定时,Mp3暂停

时间:2013-02-23 02:35:17

标签: android url service mp3

mp3在屏幕锁定时暂停...我的主要java代码...我搜索了一些信息,但没有任何帮助我。顺便说一下点击播放,然后停止,然后回到播放,应用程序崩溃,有时它需要更多点击,有时更少。有人可以帮助我。谢谢你!

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class Main extends Activity implements OnClickListener {

private ProgressBar playSeekBar;

private Button buttonPlay;

private Button buttonStopPlay;

private MediaPlayer player;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    initializeUIElements();

    initializeMediaPlayer();
}
private void initializeUIElements() {

    playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
    playSeekBar.setMax(100);
    playSeekBar.setVisibility(View.INVISIBLE);

    buttonPlay = (Button) findViewById(R.id.buttonPlay);
    buttonPlay.setOnClickListener(this);

    buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
    buttonStopPlay.setEnabled(false);
    buttonStopPlay.setOnClickListener(this);

}
public void onClick(View v) {
    if (v == buttonPlay) {
        startPlaying();
    } else if (v == buttonStopPlay) {
        stopPlaying();
    }
}  
private void startPlaying() {
    buttonStopPlay.setEnabled(true);
    buttonPlay.setEnabled(false);

    playSeekBar.setVisibility(View.VISIBLE);

    player.prepareAsync();

    player.setOnPreparedListener(new OnPreparedListener() {

        public void onPrepared(MediaPlayer mp) {
            player.start();
        }
    });

}

private void stopPlaying() {
    if (player.isPlaying()) {
        player.stop();
        player.release();
        initializeMediaPlayer();
    }

    buttonPlay.setEnabled(true);
    buttonStopPlay.setEnabled(false);
    playSeekBar.setVisibility(View.INVISIBLE);
}

private void initializeMediaPlayer() {
    player = new MediaPlayer();
    try {
        player.setDataSource("http://users1.jabry.com/mine/inna.mp3");
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            playSeekBar.setSecondaryProgress(percent);
            Log.i("Buffering", "" + percent);
        }
    });
}

@Override
protected void onPause() {
    super.onPause();
    if (player.isPlaying()) {
        player.stop();
    }
}
}

1 个答案:

答案 0 :(得分:1)

当屏幕被锁定时,你的onPause正在被调用,你明确地停止那里的玩家。