Android Activity 生命周期与音乐播放器

Android 手机开发过程中,理解好Activity的生命周期以及某种状态执行那一个方法在开发中有着事半功倍的作用。Activity 的生命周期可以主要是从创建,暂停,挂起,销毁的过程,如下图:

下面通过一个音乐播放器的例子加深自己的记忆。

音乐播放器界面:

布局的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/filename" />
    
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="If I Let You Go.mp3"
        android:id="@+id/filename"
        />
    
    <LinearLayout 
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:orientation="horizontal" >
    	
    	<Button 
    	    android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="@string/play"
    		android:id="@+id/play"
    	/>
    	
    	<Button 
    	    android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="@string/pause"
    		android:id="@+id/pause"
    	/>
    	
    	<Button 
    	    android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="@string/reset"
    		android:id="@+id/reset"
    	/>
    	
    	<Button 
    	    android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="@string/stop"
    		android:id="@+id/stop"
    	/>
    </LinearLayout>

</LinearLayout>

首先,当我们运行音乐播放器时,activity被创建,代码如下:

private static final String TAG = "AudioPlayerActivity";
	//音乐文本框输入的值
	private EditText filenameText;
	//音乐播放器
	private MediaPlayer mediaPlayer;
	//音乐名称
	private String filename;
	//音乐播放位置
	private int position;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        filenameText = (EditText)this.findViewById(R.id.filename);
        mediaPlayer = new MediaPlayer();
        
        ButtonClickListener listener = new ButtonClickListener();
        Button play = (Button)this.findViewById(R.id.play);
        Button pause = (Button)this.findViewById(R.id.pause);
        Button reset = (Button)this.findViewById(R.id.reset);
        Button stop = (Button)this.findViewById(R.id.stop);
        
        play.setOnClickListener(listener);
        pause.setOnClickListener(listener);
        reset.setOnClickListener(listener);
        stop.setOnClickListener(listener);
    }

	/**
	 * 按钮单击方法
	 * @author wmh
	 *
	 */
	private final class ButtonClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			Button button = (Button)v;
			filename = filenameText.getText().toString();
			try {
				switch (v.getId()) {
				case R.id.play:
					play();
					break;

				case R.id.pause:
					if(mediaPlayer.isPlaying()){
						mediaPlayer.pause();
						button.setText(R.string.continuePlay);
					}else{
						mediaPlayer.start();
						button.setTag(R.string.pause);
					}
					break;
				
				case R.id.reset:
					if(mediaPlayer.isPlaying()){
						mediaPlayer.seekTo(0);
					}else {
						play();
					}
					break;
				
				case R.id.stop:
					if(mediaPlayer.isPlaying()){
						mediaPlayer.stop();
					}
					break;
				}
			} catch(IOException e) {
				Log.e(TAG , e.toString());
			}
			
		}
    	
    }
	
	/**
	 * 音乐播放函数方法
	 * @throws IOException
	 */
	private void play() throws IOException {
		File audiofile = new File(Environment.getExternalStorageDirectory() , filename);
		mediaPlayer.reset();
		mediaPlayer.setDataSource(audiofile.getAbsolutePath());
		mediaPlayer.prepare();
		mediaPlayer.start();
	}

当手机在播放音乐的时候,手机有电话播入,这时,需要暂停音乐播放器,那么Activity此时就需要暂停了,那么就会执行Activity的onPause方法了,代码如下:

@Override
	protected void onPause() {
		super.onPause();
		if(mediaPlayer.isPlaying()){
			position = mediaPlayer.getCurrentPosition();
			mediaPlayer.stop();
		}
		
	}

当电话拨打结束后,重新开始播放音乐,此时Activity就被Resume了,执行的代码的如下:

@Override
	protected void onResume() {
		super.onResume();
		
		if(position > 0 && filename != null){
			try {
				play();
			} catch (IOException e) {
				Log.e(TAG, e.toString());
			}
			mediaPlayer.seekTo(position);
			position = 0;
		}
	}

当音乐播放器由于某种原因意外关闭了,Activity需要保存当前的状态,以便重新打开时可以使用结束时的状态,代码如下:

/**
	 * 当手机意外停止Activity时,保存当前播放音乐的状态
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("filename", filename);
		outState.putInt("position", position);
	}

/**
	 * 当手机内存不足强制关闭Activity时,重新执行Activity时恢复上次意外中断时的状态
	 */
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		
		this.filename = savedInstanceState.getString("filename");
		this.position = savedInstanceState.getInt("position");
		super.onRestoreInstanceState(savedInstanceState);
	}

这样,音乐播放器就完成了。

原文地址:https://www.cnblogs.com/116913829/p/2343960.html