android service 学习
2010-08-23 01:13:00 来源:WEB开发网12 public void onClick(View v) {
13
14 switch (v.getId()) {
15 case R.id.play:
16 Log.d(TAG, "onClick: binding srvice");
17 musicService.play();
18 break;
19 case R.id.stop:
20 Log.d(TAG, "onClick: stoping srvice");
21 if(musicService != null){
22 musicService.stop();
23 }
24 break;
25 case R.id.pause:
26 Log.d(TAG, "onClick: pausing srvice");
27 if(musicService != null){
28 musicService.pause();
29 }
30 break;
31 case R.id.exit:
32 Log.d(TAG, "onClick: exit");
33 this.finish();
34 break;
35 }
36 }
37
38
39private void connection(){
40 Log.d(TAG, "connecting.....");
41 Intent intent = new Intent("org.allin.android.bindService");
42 bindService(intent, sc, Context.BIND_AUTO_CREATE);
43
44 }
45private ServiceConnection sc = new ServiceConnection() {
46 @Override
47 public void onServiceDisconnected(ComponentName name) {
48 musicService = null;
49 Log.d(TAG, "in onServiceDisconnected");
50 }
51
52 @Override
53 public void onServiceConnected(ComponentName name, IBinder service) {
54 musicService = ((BindMusicService.MyBinder)(service)).getService();
55 if(musicService != null){
56 musicService.play();
57 }
58
59 Log.d(TAG, "in onServiceConnected");
60 }
61 };
62}
这里使用了bindService(intent, sc, Context.BIND_AUTO_CREATE);来启动服务的,
我们需要定义ServiceConnectionnn,并实现里面的方法,当服务绑定成功后会调用ServiceConnectionnn中的回调函数:
public void onServiceConnected(ComponentName name, IBinder service),
更多精彩
赞助商链接