ITeye博客

Android BindService

sfshine · 2012-11-18 09:57 · Android · 移动开发 · Markdown

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

 

1.调用者

 

Java代码  收藏代码

  1. package com.zhf.local;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.os.Bundle;
  8. import android.os.IBinder;
  9. /**
  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代码  收藏代码

  1. package com.zhf.local;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.Binder;
  5. import android.os.IBinder;
  6. public class MyService extends Service {
  7. private final IBinder binder=new MyBinder();
  8. @Override
  9. 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. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。