写一个小程序,在App里面实现mp3的播发,暂停,停止
步骤:
1. 新建项目,添加mp3
2. UI 制作 activity_main.xml添加3个按钮,实现播放,暂停,停止
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name"
android:layout_gravity="center"
android:src="@drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/play" />
<Button
android:id="@+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/pause"
android:layout_weight="1"
/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/stop"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
3 MainActivity.class 添加3个按钮的监控器
package com.example.hello;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button start;
private Button pause;
private Button stop;
private MediaPlayer player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)findViewById(R.id.start);
pause = (Button)findViewById(R.id.pause);
stop = (Button)findViewById(R.id.stop);
NewListener newListener = new NewListener();
start.setOnClickListener(newListener);
pause.setOnClickListener(newListener);
stop.setOnClickListener(newListener);
//MediaPlayer初始化
player = MediaPlayer.create(this, R.raw.test);
}
class NewListener implements OnClickListener{
@Override
public void onClick(View v){
switch (v.getId()) {
case R.id.start:{
//不播发就播发
if(!player.isPlaying()){
player.start();
}
break;
}
case R.id.pause:{
if(player.isPlaying()){
player.pause();
}
}
case R.id.stop:{
if(player.isPlaying()){
player.stop();
}
}
}
}
}
@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;
}
@Override
public void onDestroy(){
super.onDestroy();
if(player != null){
player.release();
}
}
}
这个小程序还没有实现后台播放音乐,还应该添加service