Service播放音樂
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button pause;
private Button stop;
private Button play;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pause = (Button) findViewById(R.id.pause);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
pause.setOnClickListener(this);
play.setOnClickListener(this);
stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// 開啟服務
Intent intent = new Intent(this, MusicService.class);
switch (v.getId()) {
case R.id.play:
// 如果是播放 傳1
intent.putExtra("command", 1);
break;
case R.id.pause:
// 如果是播放 傳1
intent.putExtra("command", 2);
break;
case R.id.stop:
// 如果是播放 傳1
intent.putExtra("command", 3);
break;
}
startService(intent);
}
}
MusicService
package com.example.servicemusicdemo;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class MusicService extends Service {
private static final String TAG = "MusicService";
private MediaPlayer mediaPlayer;
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 只是在第一次建立的時候呼叫
*/
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");
//建立服務時,建立mediaPlayer
mediaPlayer = MediaPlayer.create(this, R.raw.myhome);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 每一次startService的時候,不管服務是否開啟,都會呼叫這個方法,並且在onCreate之後.
//intent.putIntExtra(1);
//通過startService(intent);
int intExtra = intent.getIntExtra("command", 0);
Log.i(TAG, "intExtra"+intExtra);
switch (intExtra) {
case 1:
play();
break;
case 2:
pause();
break;
case 3:
stop();
break;
default:
break;
}
return super.onStartCommand(intent, flags, startId);
}
public void play() {
mediaPlayer.start();
}
public void pause() {
if (mediaPlayer != null && mediaPlayer.isPlaying())
mediaPlayer.pause();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
需要在AndroidManifest裡配置
<service android:name="com.example.servicemusicdemo.MusicService" >
</service>