资源描述
Service音乐播放器实例
Android的服务组件继承于android.app.Service类,实现一个服务,只要继承android.app.Service类,实现其生命周期中的关键方法并添加相应的服务功能就可以。像Activity等组件一样,Service也必须在AndroidManifest.xml中注册才能使用。
下面通过实现一个音乐播放服务来说明Service的实现及其生命周期,该播放服务可以使用启动方式调用也可以使用绑定方式调用。音乐播放功能使用android.media.MediaPlayer类来实现,该类提供了丰富的API接口用于实现音频、视频的播放功能,下面先简单介绍用到的几个MediaPlayer类方法。
n create(Context context, Uri uri) :通过Uri创建一个MediaPlayer对象
n create(Context context, int resid):通过资源ID创建一个MediaPlayer对象
n isPlaying():判断播放器是否正在播放 ,返回 boolean
n pause():控制播放器暂停
n prepare() :准备同步数据
n reset() :重置 MediaPlayer 对象
n setLooping(boolean looping) :设置是否循环播放
n start():控制播放器开始播放
n stop(): 控制播放器停止播放
实现音乐播放Service功能的步骤如下:
1) 新建一个Android工程,创建一个继承于android.app.Service类的PlayerService类。代码如下:
11 public class PlayerService extends Service {
2 private final String TAG = "MusicService";
3 private MediaPlayer player;
4 private final IBinder binder = new MyBinder();
5 @Override
6 public void onCreate() {
7 Log.i(TAG, "onCreate...");
8 }
9 @Override
10 public int onStartCommand(Intent intent, int flags, int sId) {
11 Log.i(TAG, "onStartCommand...");
12 String state = intent.getStringExtra("PlayerState");
13 if(state!=null)//判断客户端发送过来的指令参数
14 {
15 if (state.equals("START")) //播放
16 { start();}
17 if (state.equals("PAUSE")) //暂停
18 { pause();}
19 if (state.equals("STOP")) //停止
20 {stop();}
21 if (state.equals("STOPSERVICE")) //停止服务
22 {//调用stopSelf()关闭服务
23 stopSelf();
24 }
25 }
26 return super.onStartCommand(intent, flags, sId);
27 }
28 @Override
29//绑定方式调用时使用此函数
30 public IBinder onBind(Intent intent) {
31 Log.i(TAG, "onBind...");
32 return binder;
33 }
34 //自定义类实现使用绑定方式调用时获得服务接口
35 public class MyBinder extends Binder {
36 PlayerService getService() {
37 return PlayerService.this;
38 }
39 }
40 public void start() {
41 if (player == null) {
42 player = MediaPlayer.create(this, R.raw.hen_egg);
43 player.setLooping(false);
44 //防止prepareAsync called in state 8 错误
45 if(player!=null)
46 {player.stop();}
47 player.prepare();
48 }
49 if (!player.isPlaying()) {
50 Log.i(TAG, "player start...");
51 player.start();
52 }
53 }
54 public void pause() {
55 if (player != null && player.isPlaying()) {
56 Log.i(TAG, "player Paused...");
57 player.pause();
58 }
59 }
60 public void stop() {
61 Log.i(TAG, "player Stoped...");
62 player.stop();
63 player.prepare();
64 }
65 @Override
66 public boolean onUnbind(Intent intent) {
67 Log.i(TAG, "Service onUnbind.....");
68 stop();
69 return super.onUnbind(intent);
70 }
71 @Override
72 public void onDestroy() {
73 Log.i(TAG, "Service onDestroy.....");
74 player.stop();
75 player.release();
76 }
77 }
服务运行时首先运行onCreate()方法。
当用启动方式调用时, 之后运行的onStartCommand()方法,该方法使用Intent接收调用端传递的参数,根据参数要求执行不同的功能:播放音乐start()、暂停播放pause()和停止播放 stop(),如行12-20所示,行42的R.raw.hen_egg是一个音频文件,创建方法为,在res目录中建立一个raw文件夹,然后将一个名为hen_egg的音频文件拷贝到其中即可;
当用绑定绑定方式调用时,之后运行的是onBind()方法,该方法返回一个可以被客户端调用的服务接口,如行32所示,返回值binder的定义在行4,MyBinder类是为了使客户端能够获得服务接口,定义的一个可以实现远程调用的类,如行35-39所示,当客户端解除绑定时会调用onUnbind()方法。
服务生命结束时,最后要调用onDestroy()方法来释放资源。
2) 注册服务
打开AndroidManifest.xml,在 <application>标签中注册服务,该过程可以在Manifest编辑器中,点击选项卡,类似注册Activity来注册Service。
<service android:name="PlayerService">
<intent-filter>
<action android:name=".MP3_PLAYER"/>
</intent-filter>
</service>
3) 实现界面布局Layout
在MainActivity的Layout中添加9个按钮并设置其onClick事件,分别用于实现startService()方式调用时的四个功能和绑定方式调用时的五个功能:开始播放(playerStart)、暂停播放(playerPause)、停止播放(playerStop)、停止服务(stopService)、绑定服务(startBindService)、bind播放(playerBindStart)、bind暂停(playerBindPause)、bind停止(playerBindStop)和解除绑定(unbindService)。
4)启动方式访问音乐服务,各个功能实现代码如下:
1 /*使用Intent向服务传递数据,数据值"START"、"PAUSE"、"STOP"分别代表调用
2 服务的播放、暂停和停止播放*/
3 public void playerStart(View v)
4 {
5 Intent service=new Intent(MainActivity.this,PlayerService.class);
6 service.putExtra("PlayerState", "START");
7 startService(service);
8 }
9 public void playerPause(View v)
10 {
11 Intent service=new Intent(MainActivity.this,PlayerService.class);
12 service.putExtra("PlayerState", "PAUSE");
13 startService(service);
14 }
15 public void playerStop(View v)
16 {
17 Intent service=new Intent(MainActivity.this,PlayerService.class);
18 service.putExtra("PlayerState", "STOP");
19 startService(service);
20 }
21 public void stopService(View v)
22 {
23 Intent service=new Intent(MainActivity.this,PlayerService.class);
24 stopService(service);
25 }
startService()方式访问服务比较简单,只要将数据封装在Intent中,然后调用startService()函数启动服务就可以,如果服务已经运行,服务不会再重新创建,而是从生命周期的onStartCommand()开始运行。服务的终止可以使用 stopService(),如行24所示,也可以向服务传递一个参数,控制服务在服务类内部使用stopSelf()终止服务。
5) 绑定方式访问音乐服务
该访问方式需要先建立与服务的连接并获得服务的访问接口。功能实现代码如下:
1//首先在Activity中声明类成员pservice为服务对象
2 private PlayerService pservice=null ;
3 //建立与服务的连接,用于监视服务状态
4 private ServiceConnection conn=new ServiceConnection() {
5 @Override
6 public void onServiceDisconnected(ComponentName arg0) {
7 Log.i(TAG, "disConnected...");
8 }
9 @Override
10 public void onServiceConnected(ComponentName name, IBinder
11 service) {
12 //获得服务接口
13 pservice=((PlayerService.MyBinder)service).getService();
14 //建立连接成功后,可以马上使用获得的服务接口开始播放
15 pservice.start();
16 Log.i(TAG, "connect success...");
17 }
18 };
获得服务接口对象后,可以利用服务接口对象,直接访问服务中的方法,下面是利用服务接口对象实现播放器的代码。1 public void startBindService(View v)//启动服务
2 {
3 Intent service=new Intent(MainActivity.this,PlayerService.class);
4 bindService(service, conn, Context.BIND_AUTO_CREATE);
5 }
6 public void playerBindStart(View v)//播放
7 {
8 if(pservice!=null&&conn!=null)
9 {
10 pservice.start();
11 }
12 }
13 public void playerBindPause(View v)//暂停
14 {
15 if(pservice!=null)
16 {
17 pservice.pause();
18 }
19 }
20 public void playerBindStop(View v)//停止播放
21 {
22 if(pservice!=null)
23 {
24 pservice.stop();
25 }
26 }
27 public void unbindService(View v)//解除服务绑定
28 {
29 try
30 {
31 unbindService(conn);
32 pservice=null;
33 }
34 catch (Exception ex)
35 {
36 }
37 }
展开阅读全文