---
title: "Android BindService"
author: "sfshine"
date: "2012-11-18T09:57:44Z"
tags: []
categories: ["移动开发"]
slug: "android-bindservice"
draft: false
lastmod: "2012-11-18T09:57:44Z"
id: 1728638
url: "https://sfshine.iteye.com/blog/1728638"
---

一般情况下我们使用startService(Intent service)来启动一个服务，但这种情况下无法得到Service对象的引用，通过bindService方法启动服务则可以实现此功能。下面给一个小例子演示一下：

 

1.调用者

 

Java代码  [![收藏代码](http://que2010.iteye.com/images/icon_star.png)]()

01. package com.zhf.local;
02. import android.app.Activity;
03. import android.content.ComponentName;
04. import android.content.Context;
05. import android.content.Intent;
06. import android.content.ServiceConnection;
07. import android.os.Bundle;
08. import android.os.IBinder;
09. /\**
10. * 此例的目的就是拿到MyService的引用，从而可以引用其内部的方法和变量
11. * @author Administrator
12. \*
13. \*/
14. public class LocalServiceActivity extends Activity {
15. /\** Called when the activity is first created. \*/
16. private MyService myService;
17. @Override
18. public void onCreate(Bundle savedInstanceState) {
19. super.onCreate(savedInstanceState);
20. setContentView(R.layout.main);
21. Intent intent = new Intent(this, MyService.class);
22. bindService(intent, connection, Context.BIND\_AUTO\_CREATE);
23. }
24. private ServiceConnection connection = new ServiceConnection() {
25. @Override
26. public void onServiceDisconnected(ComponentName name) {
27. myService = null;
28. }
29. @Override
30. public void onServiceConnected(ComponentName name, IBinder service) {
31. myService = ((MyService.MyBinder) service).getService();
32. System.out.println("Service连接成功");
33. //执行Service内部自己的方法
34. myService.excute();
35. }
36. };
37. protected void onDestroy() {
38. super.onDestroy();
39. unbindService(connection);
40. };
41. }

 

 

2.服务者

 

Java代码  [![收藏代码](http://que2010.iteye.com/images/icon_star.png)]()

01. package com.zhf.local;
02. import android.app.Service;
03. import android.content.Intent;
04. import android.os.Binder;
05. import android.os.IBinder;
06. public class MyService extends Service {
07. private final IBinder binder=new MyBinder();
08. @Override
09. public IBinder onBind(Intent intent) {
10. return binder;
11. }
12. public class MyBinder extends Binder{
13. MyService getService(){
14. return MyService.this;
15. }
16. }
17. public void excute(){
18. System.out.println("通过Binder得到Service的引用来调用Service内部的方法");
19. }
20. @Override
21. public void onDestroy() {
22. //当调用者退出(即使没有调用unbindService)或者主动停止服务时会调用
23. super.onDestroy();
24. }
25. @Override
26. public boolean onUnbind(Intent intent) {
27. //当调用者退出(即使没有调用unbindService)或者主动停止服务时会调用
28. System.out.println("调用者退出了");
29. return super.onUnbind(intent);
30. }
31. }