0
public class Music extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {
private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;

private ImageButton btnPlaylist;

private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
private  MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0; 
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

ImageButton homeButton;
ImageButton backButton;
private boolean isActivityRestarting;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.player);

    // All player buttons
    btnPlay = (ImageButton) findViewById(R.id.play_btn);
    btnForward = (ImageButton) findViewById(R.id.forword_btn);
    btnBackward = (ImageButton) findViewById(R.id.backword_btn);

    btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);

    songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
    songTitleLabel = (TextView) findViewById(R.id.songTitle);
    songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

    // Mediaplayer
    mp = new MediaPlayer();
    songManager = new SongsManager();
    utils = new Utilities();


     homeButton = (ImageButton) findViewById(R.id.home_btn);
        backButton = (ImageButton) findViewById(R.id.back_btn);
        homeButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v){
                Intent openStartingPoint = new Intent("org.example.app.betar.HOME");
                startActivity(openStartingPoint);
            }
        });

        backButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v){
                Intent openStartingPoint = new Intent("org.example.app.betar.HOME");
                startActivity(openStartingPoint);
            }
        });
    // Listeners
    songProgressBar.setOnSeekBarChangeListener(this); // Important
    mp.setOnCompletionListener(this); // Important

    // Getting all songs list
    songsList = songManager.getPlayList();

    // By default play first song
    playSong(0);

    /**
     * Play button click event
     * plays a song and changes button to pause image
     * pauses a song and changes button to play image
     * */
    btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check for already playing
            if(mp.isPlaying()){
                if(mp!=null){
                    mp.pause();
                    // Changing button image to play button
                    btnPlay.setImageResource(R.drawable.btn_play);
                }
            }else{
                // Resume song
                if(mp!=null){
                    mp.start();
                    // Changing button image to pause button
                    btnPlay.setImageResource(R.drawable.btn_pause);
                }
            }

        }
    });

    /**
     * Forward button click event
     * Forwards song specified seconds
     * */
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // get current song position                
            int currentPosition = mp.getCurrentPosition();
            // check if seekForward time is lesser than song duration
            if(currentPosition + seekForwardTime <= mp.getDuration()){
                // forward song
                mp.seekTo(currentPosition + seekForwardTime);
            }else{
                // forward to end position
                mp.seekTo(mp.getDuration());
            }
        }
    });

    /**
     * Backward button click event
     * Backward song to specified seconds
     * */
    btnBackward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // get current song position                
            int currentPosition = mp.getCurrentPosition();
            // check if seekBackward time is greater than 0 sec
            if(currentPosition - seekBackwardTime >= 0){
                // forward song
                mp.seekTo(currentPosition - seekBackwardTime);
            }else{
                // backward to starting position
                mp.seekTo(0);
            }

        }
    });









    /**
     * Button Click event for Play list click event
     * Launches list activity which displays list of songs
     * */
    btnPlaylist.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
            startActivityForResult(i, 100);         
        }
    });

}

/**
 * Receiving song index from playlist view
 * and play the song
 * */
@Override
protected void onActivityResult(int requestCode,
                                 int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == 100){
         currentSongIndex = data.getExtras().getInt("songIndex");
         // play selected song
         playSong(currentSongIndex);
    }

}

/**
 * Function to play a song
 * @param songIndex - index of song
 * */
public void  playSong(int songIndex){
    // Play song
    try {
        mp.reset();
        mp.setDataSource(songsList.get(songIndex).get("songPath"));
        mp.prepare();
        mp.start();
        // Displaying Song title
        String songTitle = songsList.get(songIndex).get("songTitle");
        songTitleLabel.setText(songTitle);

        // Changing Button Image to pause image
        btnPlay.setImageResource(R.drawable.btn_pause);

        // set Progress bar values
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);

        // Updating progress bar
        updateProgressBar();            
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Update timer on seekbar
 * */
public void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask, 100);        
}   

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {
           long totalDuration = mp.getDuration();
           long currentDuration = mp.getCurrentPosition();

           // Displaying Total Duration time
           songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
           // Displaying time completed playing
           songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

           // Updating progress bar
           int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
           //Log.d("Progress", ""+progress);
           songProgressBar.setProgress(progress);

           // Running this thread after 100 milliseconds
           mHandler.postDelayed(this, 100);
       }
    };

/**
 * 
 * */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

}

/**
 * When user starts moving the progress handler
 * */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // remove message Handler from updating progress bar
    mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
 * When user stops moving the progress hanlder
 * */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    // forward or backward to certain seconds
    mp.seekTo(currentPosition);

    // update timer progress again
    updateProgressBar();
}

/**
 * On Song Playing completed
 * if repeat is ON play same song again
 * if shuffle is ON play random song
 * */
@Override
public void onCompletion(MediaPlayer arg0) {

    // check for repeat is ON or OFF

        // no repeat or shuffle ON - play next song
        if(currentSongIndex < (songsList.size() - 1)){
            playSong(currentSongIndex + 1);
            currentSongIndex = currentSongIndex + 1;
        }else{
            // play first song
            playSong(0);
            currentSongIndex = 0;
        }
    }


@Override
 public void onDestroy(){
 super.onDestroy();
    mp.release();
 }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_BACK) {
     //preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
     return true;
     }
     return super.onKeyDown(keyCode, event);    
}


}

我使用android构建了音乐播放器这个播放器是这个应用程序中更多活动的一个我从主页调用活动播放器但是当我回到主页然后再次调用播放器的活动你再次播放歌曲并且仍然播放旧音乐

当我打电话给活动播放器时,我需要继续播放歌曲,回到现在

我使用 startActivity 从主页调用活动播放器

请帮帮我

4

4 回答 4

0

在 Activity 的方法中创建 MediaPlayeronCreate而不检查 MediaPlayer 实例是否已经存在不是一个好主意。您可能想熟悉 Android 中的Activity 生命周期。您的 Activity 可能会重新创建,例如,如果它由于移动到背景而停止,或者由于用户倾斜设备时的方向变化而停止。因此,您至少应该覆盖所有相关的回调(onStop,onResume等),以便您可以以适当的方式释放和分配资源。

更好的是在Service中管理 MediaPlayer ,因为服务意味着在后台运行很长时间。Android 文档在描述服务时甚至提到了这个特殊的用例:“例如,当用户在不同的应用程序中时,服务可能会在后台播放音乐”

于 2013-03-07T11:57:02.647 回答
0

在代码中:

@Override
 public void onDestroy(){
 super.onDestroy();
    mp.release();
 }

mp.release 编辑 mp.pause

@Override
 public void onDestroy(){
 super.onDestroy();
    mp.pause();
 }
于 2014-07-23T16:20:46.060 回答
0

在 Android 中 onBackPress() 或 onPause() 停止媒体播放器并完成() Activity。

谢谢

于 2013-03-07T07:28:07.627 回答
0

我知道这为时已晚,但希望它能奏效。将媒体播放器 mp 指定为静态。比如私有静态MediaPLayer mp。这将保存 mp 的一个实例,以便它只是被重用而不是重新创建。希望能帮助到你。

于 2014-02-05T21:29:49.580 回答