1、Service介紹
官方解釋:A Service
is
an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another
application
也就是說Service是一個沒有提供用戶界面而能夠提供在後臺運行的構件,其他應用能啓動一個Service,即使是切換到其他的應用它還能在後臺運行。
2、Service的生命週期
Android Service的生命週期並不像Activity那麼複雜,它只繼承了onCreate(),onStart(),onDestroy()三個方法,當我們第一次啓動Service時,先後調用了onCreate(),onStart()這兩個方法,當停止Service時,則執行onDestroy()方法,這裏需要注意的是,如果Service已經啓動了,當我們再次啓動Service時,不會在執行onCreate()方法,而是直接執行onStart()方法。
3、下面舉個播放音樂的例子:
首先在res創建目錄raw,然後在裏面添加MP3文件
繼承一個Service類:
package com.Moruna.studys;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class MyService extends Service {
private MediaPlayer mp;
@Override
public void onCreate() {
// TODO Auto-generated method stub
// 初始化音樂資源
try {
System.out.println("create player");
// 創建MediaPlayer對象
mp = new MediaPlayer();
mp = MediaPlayer.create(MyService.this, R.raw.alarm);
// mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
// 開始播放音樂
mp.start();
// 音樂播放完畢的事件處理
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// 循環播放
try {
mp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// 播放音樂時發生錯誤的事件處理
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
// 釋放資源
try {
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
// 服務停止時停止播放音樂並釋放資源
mp.stop();
mp.release();
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
在Activity中調用MyService啓動音樂或關閉音樂,這時就算退出應用,如果沒有關閉Service,它還會在後臺播放直至關閉
在Alarm這個Activity繼承類中啓動音樂:
// 播放鬧鈴
Intent intentSV = new Intent(Alarm.this, MyService.class);
startService(intentSV);
在Alarm這個Activity繼承類中關閉音樂:
//關閉鬧鈴聲
Intent intentSV = new Intent(Alarm.this, MyService.class);
stopService(intentSV);
這樣就能實現Service在後臺播放所要播放的音樂,當然,在哪裏需要啓動或關閉音樂看你自己個人需求。
另需要注意一點的是,別忘了註冊:
在AndroidManifest.xml中的Application中加入:
<service android:name=".MyService" />