本事實驗使用service實作背景音樂功能,主要使用MediaPlayer控件實作。
service 你可以了解成沒有的界面的activity,它是跑在背景的程式,所謂背景是相對于可以被看得到的程式的,背景程式是不能直接互動的程式。
程式中使用Binder機制,而Binder機制在很多很多的Service就是通過Binder機制來和用戶端通訊互動的。
binder主要是用來程序間通信的,但也可用在和本地service通信。
本次實驗使用MediaPlayer對象
主要的方法:
- create(url);是從url中擷取一個應用自帶的mp3檔案.
- setOnCompletionListener();是為對象添加一個監聽事件,用于監聽事件完成.
- setLooping();設定音樂循環播放。
建立一個android項目。
1. 在res檔案下建立raw檔案夾把mp3檔案在此目錄下
2. 建立含有一個播放一個停止的按鈕的布局檔案
3. 建立一個AudioService類。在清單AndroidManifest.xml中添加
AudioService.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對象添加一個監聽事件,用于監聽事件完成
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();
}
}
}
}
在MainActivity.java中添加
public class MainActivity extends Activity {
Button playing, stop;// 聲明控件變量
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findId();
playing.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, AudioService.class));// 啟動service服務轉向AudioService
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(MainActivity.this, AudioService.class));// 停止service
}
});
}
void findId() {// 擷取控件id
playing = (Button) findViewById(R.id.playing);
stop = (Button) findViewById(R.id.stop);
}
protected void onResume() {// 在 Activity 從 Pause 狀态轉換到 Active 狀态時被調用。
super.onResume();
startService(new Intent(MainActivity.this, AudioService.class));
}
@Override
protected void onDestroy() {// 防止程式退出後音樂不停止問題。在destroy中停止服務
// TODO Auto-generated method stub
super.onDestroy();
stopService(new Intent(MainActivity.this, AudioService.class));// 停止service
}
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;
}
}
- 啟動程式即可
本次代碼實作http://download.csdn.net/detail/kong_z/8859389