代码内,我添加了三个按键:Start Activity;Stop Activity 和 Suspend Activity
它们分别用来播放音乐,停止播放音乐和暂停播放。
package mth.android;
import android.app.Activity;import android.media.MediaPlayer;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;
public class AndroidActivity extends Activity implements View.OnClickListener { // Define a media player private MediaPlayer mediaPlayer = null; private int curPos = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //final View textDisplayer = this.findViewById(R.id.displayText); //final TextView textDisplayer = (TextView) this.findViewById(R.id.displayText); Button startActivityButton = (Button)this.findViewById(R.id.startAndroidActivity); startActivityButton.setOnClickListener(this); Button stopActivityButton = (Button)this.findViewById(R.id.stopAndroidActivity); stopActivityButton.setOnClickListener(this); Button suspendActivityButton = (Button)this.findViewById(R.id.suspendAndroidActivity); suspendActivityButton.setOnClickListener(this); /* Button startActivityButton = (Button)this.findViewById(R.id.startAndroidActivity); startActivityButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) { // TODO Auto-generated method stub display(textDisplayer); } }); */ /* View startActivityButton = this.findViewById(R.id.startAndroidActivity); startActivityButton.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { // TODO Auto-generated method stub textDisplayer.setText("Hello World"); textDisplayer.setBackgroundColor(0xFFFFFFFF); } } ); */ /* TextView text = new TextView(this); text.setText("Hello World"); setContentView(text); */ } public void display(TextView tv) { tv.setText("Hello world"); tv.setBackgroundColor(0xFFFFFF00); }
public void onClick(View v) { //int curPos = 0;; switch (v.getId()) { case R.id.startAndroidActivity: // TODO Auto-generated method stub final TextView textDisplayer = (TextView) this.findViewById(R.id.displayText); textDisplayer.setText("Hello world"); textDisplayer.setBackgroundColor(BIND_AUTO_CREATE); // Start media player mediaPlayer = MediaPlayer.create(this, R.raw.just_one_last_dance); mediaPlayer.seekTo(0); mediaPlayer.start(); break; case R.id.stopAndroidActivity: mediaPlayer.stop(); break; case R.id.suspendAndroidActivity: if(true == mediaPlayer.isPlaying()) { curPos = mediaPlayer.getCurrentPosition(); mediaPlayer.pause(); } else { mediaPlayer.seekTo(curPos); mediaPlayer.start(); } break; default: break; } }}