如何在onResume Android上暂停时恢复音频播放器

时间:2014-08-12 14:40:49

标签: android position android-mediaplayer onresume onpause

以下媒体播放器可以正常工作,但每次暂停活动时(例如屏幕关闭或来电),媒体播放器都会从位置0开始,但不会处于暂停位置。

有没有人提示,当活动恢复时,如何设置最后一个位置以让玩家在最后一个位置恢复?

MediaPlayer活动:

public class PoiView extends ActionBarActivity implements MediaPlayer.OnCompletionListener {


    MediaPlayer mediaPlayer;
    private double startTime = 0;
    private double finalTime = 0;
    private Handler myHandler = new Handler();
    private SeekBar seekbar;
    private ImageButton playButton,pauseButton;
    public static int oneTimeOnly = 0;
    public TextView startTimeField,endTimeField;
    boolean isPrepared = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poi_view);

        getActionBar().setDisplayHomeAsUpEnabled(true);

        seekbar = (SeekBar)findViewById(R.id.seekBar);
        playButton = (ImageButton)findViewById(R.id.imagePlay);
        pauseButton = (ImageButton)findViewById(R.id.imagePause);
        startTimeField =(TextView)findViewById(R.id.textStart);

        seekbar.setClickable(false);
        pauseButton.setEnabled(false);
        endTimeField =(TextView)findViewById(R.id.textStop);

        try {
            //mediaPlayer.prepare();
            int resID=getResources().getIdentifier(poiAudio, "raw", getPackageName());
            mediaPlayer = MediaPlayer.create(this, resID);
            isPrepared = true;
            mediaPlayer.setOnCompletionListener(this);
        } catch (NullPointerException e) {
            Context context = getApplicationContext();
            CharSequence text = getResources().getString(R.string.audioerror);
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, text, duration);
            toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            toast.show();
        }
    }

    public void play(View view) {
        Toast.makeText(getApplicationContext(), R.string.audio_play,
                Toast.LENGTH_SHORT).show();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mediaPlayer.start();
        finalTime = mediaPlayer.getDuration();
        startTime = mediaPlayer.getCurrentPosition();
        if (oneTimeOnly == 0) {
            seekbar.setMax((int) finalTime);
            oneTimeOnly = 1;
        }
        endTimeField.setText(String.format("%d min, %d sec",
                        TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
                        TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
                                        toMinutes((long) finalTime)))
        );
        startTimeField.setText(String.format("%d min, %d sec",
                        TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                        TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
                                        toMinutes((long) startTime)))
        );
        seekbar.setProgress((int)startTime);
        myHandler.postDelayed(UpdateSongTime,100);
        pauseButton.setEnabled(true);
        playButton.setEnabled(false);
    }


    private Runnable UpdateSongTime = new Runnable() {
        public void run() {
            startTime = mediaPlayer.getCurrentPosition();
            startTimeField.setText(String.format("%d min, %d sec",
                            TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                            TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
                                            toMinutes((long) startTime)))
            );
            seekbar.setProgress((int)startTime);
            myHandler.postDelayed(this, 100);
        }
    };

    public void pause(View view){
        Toast.makeText(getApplicationContext(), R.string.audio_pause,
                Toast.LENGTH_SHORT).show();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mediaPlayer.pause();
        pauseButton.setEnabled(false);
        playButton.setEnabled(true);
        startTime = mediaPlayer.getCurrentPosition();
    }

    @Override
    public void onSaveInstanceState (Bundle outState) {
        super.onSaveInstanceState(outState);

    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // Restore UI state from the savedInstanceState.
        // This bundle has also been passed to onCreate.

    }

    @Override
    public void onPause() {
        super.onPause();
        myHandler.removeCallbacksAndMessages(null);
        Bundle b = new Bundle();
        if (mediaPlayer != null) {
            b.putDouble("starttime", startTime);
            //mediaPlayer.release();
            pauseButton.setEnabled(false);
            playButton.setEnabled(true);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Bundle b = getIntent().getExtras();
        if (mediaPlayer == null)       {
        int resID=getResources().getIdentifier(poiAudio, "raw", getPackageName());
        mediaPlayer = MediaPlayer.create(this, resID);
        } else {
            //mediaPlayer.pause();
            startTime = mediaPlayer.getCurrentPosition();
            seekbar.setProgress((int) startTime);
            mediaPlayer.seekTo((int) startTime);
        }

    }

    @Override
    public void onRestart() {
        super.onRestart();
        Bundle b = getIntent().getExtras();
        if (mediaPlayer == null)       {
            int resID=getResources().getIdentifier(poiAudio, "raw", getPackageName());
            mediaPlayer = MediaPlayer.create(this, resID);
            startTime = mediaPlayer.getCurrentPosition();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {

        mediaPlayer.stop();
        mediaPlayer.release();
        pauseButton.setEnabled(false);
        playButton.setEnabled(true);
        startTime = 0;
        seekbar.setProgress((int) startTime);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

    public class MusicIntentReceiver extends android.content.BroadcastReceiver {
        @Override
        public void onReceive(Context ctx, Intent intent) {
            if (intent.getAction().equals(
                    android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
                mediaPlayer.pause();
                pauseButton.setEnabled(false);
                playButton.setEnabled(true);
                startTime = mediaPlayer.getCurrentPosition();
                seekbar.setProgress((int)startTime);
                Bundle b = new Bundle();
                b.putDouble("starttime", startTime);
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        myHandler.removeCallbacksAndMessages(null);
        Bundle b = new Bundle();
        b.putDouble("starttime", startTime);

    }

    private void unbindDrawables(View view)
    {
        if (view.getBackground() != null)
        {
            view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup && !(view instanceof AdapterView))
        {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
            {
                unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindDrawables(findViewById(R.id.imagePoi));
        System.gc();
        Bundle b = new Bundle();
        b.putDouble("starttime", startTime);
        if (mediaPlayer != null) mediaPlayer.release();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.poi_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                Intent backrouteview = NavUtils.getParentActivityIntent(this);
                backrouteview.putExtra("route", routeSave);
                backrouteview.putExtra("titel_route", routeTitel);
                startActivity(backrouteview);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

以下是修改后的主要活动文件src / com.example.mediaplayer / MainActivity.java的内容。

package com.example.mediaplayer;

import java.util.concurrent.TimeUnit;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

   public TextView songName,startTimeField,endTimeField;
   private MediaPlayer mediaPlayer;
   private double startTime = 0;
   private double finalTime = 0;
   private Handler myHandler = new Handler();;
   private int forwardTime = 5000; 
   private int backwardTime = 5000;
   private SeekBar seekbar;
   private ImageButton playButton,pauseButton;
   public static int oneTimeOnly = 0;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      songName = (TextView)findViewById(R.id.textView4);
      startTimeField =(TextView)findViewById(R.id.textView1);
      endTimeField =(TextView)findViewById(R.id.textView2);
      seekbar = (SeekBar)findViewById(R.id.seekBar1);
      playButton = (ImageButton)findViewById(R.id.imageButton1);
      pauseButton = (ImageButton)findViewById(R.id.imageButton2);
      songName.setText("song.mp3");
      mediaPlayer = MediaPlayer.create(this, R.raw.song);
      seekbar.setClickable(false);
      pauseButton.setEnabled(false);

   }

   public void play(View view){
   Toast.makeText(getApplicationContext(), "Playing sound", 
   Toast.LENGTH_SHORT).show();
      mediaPlayer.start();
      finalTime = mediaPlayer.getDuration();
      startTime = mediaPlayer.getCurrentPosition();
      if(oneTimeOnly == 0){
         seekbar.setMax((int) finalTime);
         oneTimeOnly = 1;
      } 

      endTimeField.setText(String.format("%d min, %d sec", 
         TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
         TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - 
         TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
         toMinutes((long) finalTime)))
      );
      startTimeField.setText(String.format("%d min, %d sec", 
         TimeUnit.MILLISECONDS.toMinutes((long) startTime),
         TimeUnit.MILLISECONDS.toSeconds((long) startTime) - 
         TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
         toMinutes((long) startTime)))
      );
      seekbar.setProgress((int)startTime);
      myHandler.postDelayed(UpdateSongTime,100);
      pauseButton.setEnabled(true);
      playButton.setEnabled(false);
   }

   private Runnable UpdateSongTime = new Runnable() {
      public void run() {
         startTime = mediaPlayer.getCurrentPosition();
         startTimeField.setText(String.format("%d min, %d sec", 
            TimeUnit.MILLISECONDS.toMinutes((long) startTime),
            TimeUnit.MILLISECONDS.toSeconds((long) startTime) - 
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
            toMinutes((long) startTime)))
         );
         seekbar.setProgress((int)startTime);
         myHandler.postDelayed(this, 100);
      }
   };
   public void pause(View view){
      Toast.makeText(getApplicationContext(), "Pausing sound", 
      Toast.LENGTH_SHORT).show();

      mediaPlayer.pause();
      pauseButton.setEnabled(false);
      playButton.setEnabled(true);
   }    
   public void forward(View view){
      int temp = (int)startTime;
      if((temp+forwardTime)<=finalTime){
         startTime = startTime + forwardTime;
         mediaPlayer.seekTo((int) startTime);
      }
      else{
         Toast.makeText(getApplicationContext(), 
         "Cannot jump forward 5 seconds", 
         Toast.LENGTH_SHORT).show();
      }

   }
   public void rewind(View view){
      int temp = (int)startTime;
      if((temp-backwardTime)>0){
         startTime = startTime - backwardTime;
         mediaPlayer.seekTo((int) startTime);
      }
      else{
         Toast.makeText(getApplicationContext(), 
         "Cannot jump backward 5 seconds",
         Toast.LENGTH_SHORT).show();
      }

   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
   // Inflate the menu; this adds items to the action bar if it is present.
   getMenuInflater().inflate(R.menu.main, menu);
   return true;
   }

 }

以下是xml res / layout / activity_main.xml的修改内容。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <ImageButton
      android:id="@+id/imageButton3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:layout_marginBottom="14dp"
      android:onClick="forward"
      android:src="@android:drawable/ic_media_ff" />

   <ImageButton
      android:id="@+id/imageButton4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentRight="true"
      android:layout_alignTop="@+id/imageButton2"
      android:layout_marginLeft="22dp"
      android:layout_toRightOf="@+id/imageButton2"
      android:onClick="rewind"
      android:src="@android:drawable/ic_media_rew" />

   <ImageButton
      android:id="@+id/imageButton2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@+id/imageButton1"
      android:layout_marginLeft="14dp"
      android:layout_toRightOf="@+id/imageButton1"
      android:onClick="pause"
      android:src="@android:drawable/ic_media_pause" />

   <ImageButton
      android:id="@+id/imageButton1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@+id/imageButton3"
      android:layout_marginLeft="24dp"
      android:layout_toRightOf="@+id/imageButton3"
      android:onClick="play"
      android:src="@android:drawable/ic_media_play" />

   <SeekBar
      android:id="@+id/seekBar1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" 
      android:layout_above="@+id/imageButton3"
      android:layout_toLeftOf="@+id/textView2"
      android:layout_toRightOf="@+id/textView1" />

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignRight="@+id/imageButton3"
      android:layout_alignTop="@+id/seekBar1"
      android:text="@string/inital_Time"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/imageButton4"
      android:layout_alignTop="@+id/seekBar1"
      android:text="@string/inital_Time"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <TextView
      android:id="@+id/textView3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/imageButton3"
      android:text="@string/hello_world"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <ImageView
      android:id="@+id/imageView1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:layout_below="@+id/textView3"
      android:src="@drawable/ic_launcher" />

   <TextView
      android:id="@+id/textView4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/textView3"
      android:layout_alignBottom="@+id/textView3"
      android:layout_toRightOf="@+id/imageButton1"
      android:text="TextView" />

</RelativeLayout>

以下是res / values / string.xml的内容。

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">MediaPlayer</string>
   <string name="action_settings">Settings</string> 
   <string name="hello_world">Now Playing:</string>
   <string name="inital_Time">0 min, 0 sec</string>

</resources>

以下是AndroidManifest.xml文件的内容。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.mediaplayer"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.mediaplayer.MainActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>