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);
//结束服务
|