1、背景音乐效果图如下所示
2、activity_main.xml文件布局代码如下所示
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:text="@string/btnPlay" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btnStop" />
</LinearLayout>
3、mainactivity.java类代码如下
public class MainActivity extends Activity {
//创建Button对象
private Button btnPlayClick;
private Button btnStopClick;
//创建Intent
Intent intent = new Intent(MainActivity.this,
AudioService.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取Button对象
btnPlayClick=(Button) findViewById(R.id.btnPlay);
btnStopClick=(Button) findViewById(R.id.btnStop);
//播放
btnPlayClick.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(intent);
}
});
//暂停
btnStopClick.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(intent);
}
});
}
@Override
protected void onResume() {
super.onResume();
stopService(new Intent(this,AudioService.class));
}
@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;
}
4、Service.java类代码如下
public class AudioService extends Service implements
MediaPlayer.OnCompletionListener {
// 实例化MediaPlayer对象
MediaPlayer player;
private final IBinder binder = new AudioBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public void onCreate() {
super.onCreate();
// 从raw文件夹中获取一个应用自带的mp3文件
player = MediaPlayer.create(this, R.raw.qq);
player.setOnCompletionListener(this);
player.setLooping(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (!player.isPlaying()) {
new MusicPlayThread().start();
}
else player.isPlaying();
return START_STICKY;
}
/**
* 当Audio播放完的时候触发该动作
*/
public void onCompletion(MediaPlayer mp) {
stopSelf();// 结束了,则结束Service
}
public void onDestroy() {
super.onDestroy();
if (player.isPlaying()) {
player.stop();
}
player.release();
}
// 为了和Activity交互,我们需要定义一个Binder对象
public class AudioBinder extends Binder {
// 返回Service对象
public AudioService getService() {
return AudioService.this;
}
}
private class MusicPlayThread extends Thread {
public void run() {
if (!player.isPlaying()) {
player.start();
}
}
}