1,創建一個MusicPlayService繼承Service,並重寫onCreat()方法和onStartCommand(...)方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class MusicPlayService extends Service{ @Override public void onCreate() { // TODO Auto-generated method stub Log.e(TAG, "MusicSerice onCreate()" ); //musicplay=BackgroundMusicPlay.getBackgroundMusicPlay(this); super .onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "MusicSerice---> onStartCommand()" ); playMusic(); return super .onStartCommand(intent, flags, startId); } public void playMusic() { musicplay.musicPlay(); // mp=MediaPlayer.create(getApplicationContext(), R.raw.newgalactic); // mp.setLooping(true); // mp.start(); } } |
注意:由於onStart(...)方法在level 2.0之後已經失效,所以2.0之後用onStartCommand代替,具體請查看API文檔http://tool.oschina.net/apidocs/apidoc?api=android/reference
2,在activity中通過startService(...)調用服務
1
2
3
|
Intent intent2= new Intent(ShorMusicPlay. this , MusicPlayService. class ); startService(intent2); //啓動服務 stopService(intent2); //結束服務
|