[翻译]API Guides - Bound Services
官方文档原文地址:http://developer.android.com/guide/components/bound-services.html
一个Bound Service是一个客户端-服务器接口的服务。一个Bound Service允许组件(像activity)绑定一个service,发送请求,接受结果,甚至进行进程间通信。一个Bound Service通常只在他向其它组件提供服务的时候运行,不会无法确定的运行在后台的。
publicclassLocalServiceextendsService{// Binder given to clientsprivatefinalIBinder mBinder =newLocalBinder();// Random number generatorprivatefinalRandom mGenerator =newRandom();/*** Class used for the client Binder. Because we know this service always* runs in the same process as its clients, we don't need to deal with IPC.*/publicclassLocalBinderextendsBinder{LocalService getService(){// Return this instance of LocalService so clients can call public methodsreturnLocalService.this;}}@OverridepublicIBinder onBind(Intent intent){return mBinder;}/** method for clients */publicint getRandomNumber(){return mGenerator.nextInt(100);} }
publicclassBindingActivityextendsActivity{LocalService mService;boolean mBound =false;@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);}@Overrideprotectedvoid onStart(){super.onStart();// Bind to LocalServiceIntent intent =newIntent(this,LocalService.class);bindService(intent, mConnection,Context.BIND_AUTO_CREATE);}@Overrideprotectedvoid onStop(){super.onStop();// Unbind from the serviceif(mBound){unbindService(mConnection);mBound =false;}}/** Called when a button is clicked (the button in the layout file attaches to* this method with the android:onClick attribute) */publicvoid onButtonClick(View v){if(mBound){// Call a method from the LocalService.// However, if this call were something that might hang, then this request should// occur in a separate thread to avoid slowing down the activity performance.int num = mService.getRandomNumber();Toast.makeText(this,"number: "+ num,Toast.LENGTH_SHORT).show();}}/** Defines callbacks for service binding, passed to bindService() */privateServiceConnection mConnection =newServiceConnection(){@Overridepublicvoid onServiceConnected(ComponentName className,IBinder service){// We've bound to LocalService, cast the IBinder and get LocalService instanceLocalBinder binder =(LocalBinder) service;mService = binder.getService();mBound =true;}@Overridepublicvoid onServiceDisconnected(ComponentName arg0){mBound =false;}}; }
- service实现一个Handler为从客户端的每一个调用接收回调。
- Hander用来创建Messenger对象。
- Messenger创建IBinder对象,用于客户端从service的onBind()方法了获取IBinder。
- 客户端使用IBinder来初始化Messenger,这样客户端可以使用它给service发送Message对象。
- service从它的handle里接收每一个Message,准确的说,是在handleMessage()方法里。
在这种方式里,没有任何在service里的方法给客户端调用。取而代之的是,客户端发送消息给service的handler获取。
publicclassMessengerServiceextendsService{/** Command to the service to display a message */staticfinalint MSG_SAY_HELLO =1;/*** Handler of incoming messages from clients.*/classIncomingHandlerextendsHandler{@Overridepublicvoid handleMessage(Message msg){switch(msg.what){case MSG_SAY_HELLO:Toast.makeText(getApplicationContext(),"hello!",Toast.LENGTH_SHORT).show();break;default:super.handleMessage(msg);}}}/*** Target we publish for clients to send messages to IncomingHandler.*/finalMessenger mMessenger =newMessenger(newIncomingHandler());/*** When binding to the service, we return an interface to our messenger* for sending messages to the service.*/@OverridepublicIBinder onBind(Intent intent){Toast.makeText(getApplicationContext(),"binding",Toast.LENGTH_SHORT).show();return mMessenger.getBinder();} }
publicclassActivityMessengerextendsActivity{/** Messenger for communicating with the service. */Messenger mService =null;/** Flag indicating whether we have called bind on the service. */boolean mBound;/*** Class for interacting with the main interface of the service.*/privateServiceConnection mConnection =newServiceConnection(){publicvoid onServiceConnected(ComponentName className,IBinder service){// This is called when the connection with the service has been// established, giving us the object we can use to// interact with the service. We are communicating with the// service using a Messenger, so here we get a client-side// representation of that from the raw IBinder object.mService =newMessenger(service);mBound =true;}publicvoid onServiceDisconnected(ComponentName className){// This is called when the connection with the service has been// unexpectedly disconnected -- that is, its process crashed.mService =null;mBound =false;}};publicvoid sayHello(View v){if(!mBound)return;// Create and send a message to the service, using a supported 'what' valueMessage msg =Message.obtain(null,MessengerService.MSG_SAY_HELLO,0,0);try{mService.send(msg);}catch(RemoteException e){e.printStackTrace();}}@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);}@Overrideprotectedvoid onStart(){super.onStart();// Bind to the servicebindService(newIntent(this,MessengerService.class), mConnection,Context.BIND_AUTO_CREATE);}@Overrideprotectedvoid onStop(){super.onStop();// Unbind from the serviceif(mBound){unbindService(mConnection);mBound =false;}} }
LocalService mService; privateServiceConnection mConnection =newServiceConnection(){// Called when the connection with the service is established publicvoid onServiceConnected(ComponentName className,IBinder service){// Because we have bound to an explicit// service that is running in our own process, we can// cast its IBinder to a concrete class and directly access it.LocalBinder binder =(LocalBinder) service;mService = binder.getService();mBound =true;}// Called when the connection with the service disconnects unexpectedly publicvoid onServiceDisconnected(ComponentName className){Log.e(TAG,"onServiceDisconnected");mBound =false;} };
Intent intent =newIntent(this,LocalService.class); bindService(intent, mConnection,Context.BIND_AUTO_CREATE);
- bindService()的第一个参数是一个指定了绑定哪一个service的Intent对象(虽然intent也可以是隐式的)。
- 第二个参数是ServiceConnection对象。
- 第三个参数是一个绑定可选的标示符。通常为了去创建一个不存在的service,应该使用BIND_AUTO_CREATE。其它的值是BIND_DEBUG_UNBIND和BIND_NOT_FOREGROUND,或者0。
- 你应该总是捕获DeadObjectException异常,这个异常将在连接被破坏的时候抛出,也是唯一一个通过远程方法抛出的异常。
- 在进程之间,对象的引用被计数。( Objects are reference counted across processes)
- 你应该总是在你客户端的生命周期里成对的去绑定和解绑,匹配与连接与断开的时候。
- 如果你仅仅是希望service与你的activity交互在可见的时候,你应该在onStart()方法中绑定,onStop()方法中解绑。
- 如果你希望你的activity能够在自己停止前一直能接收到反馈结果,你应该在onCreate()里绑定,在onDestroy()里解绑。注意,这意味着你的activity需要一直使用service(甚至是在后台。)所以,如果service在另一个进程里,所以你应该提高你进程的权重,这样系统就不太可能会杀掉它了。
转载于:https://www.cnblogs.com/kross/p/3423877.html
[翻译]API Guides - Bound Services相关推荐
- Android API 指南 - Android API Guides
http://developer.android.com/intl/zh-CN/guide/components/index.html ) 请找到自己要翻译的部分,按下面的'链接规范'添加到下面列表中 ...
- Google翻译API(B/S调用和C/S调用)
浏览器调用: <html><head><script type="text/javascript" src="http://www.goog ...
- python有道翻译接口-Python通过调用有道翻译api实现翻译功能示例
本文实例讲述了Python通过调用有道翻译api实现翻译功能.分享给大家供大家参考,具体如下: 通过调用有道翻译的api,实现中译英.其他语言译中文 Python代码: # coding=utf-8 ...
- php 百度收录api_php使用百度翻译api示例分享
这篇文章主要介绍了php使用百度翻译api示例,需要的朋友可以参考下 百度翻译API的PHP代码,测试可以实现,不过英译中可能需要转换编码. function language($value,$fro ...
- Python 调用有道翻译api接口翻译外文网站的整篇西班牙文实战演示
Python 调用有道翻译 api 接口翻译整篇西班牙文实战演示 第一章:翻译效果展示 ① 翻译文章示例一[阿尔卡拉门的无海摩纳哥:"不到4万欧元,你就不能在这里租任何东西."] ...
- 百度翻译API的使用
百度翻译API 使用 关注 "弋凡"(YiFan)微信公众号吧 记录简单笔记 做你的最爱 1,注册百度翻译平台账号 http://api.fanyi.baidu.com/ 2,得到 ...
- Bound Services
原文URL:Bound Services (1) Bound service在客户/服务器模式中充当服务端.一个Bound Service允许组件(比如Activities)绑定到该Service上, ...
- 利用Bing翻译API简单的实现一个翻译工具
常见的翻译服务提供商有Google和微软,它们的在线翻译地址如下: Bing翻译: http://www.microsofttranslator.com/?FORM=R5FD Google翻译: ht ...
- 为支持两个语言版本,我基于谷歌翻译API写了一款自动翻译的 webpack 插件
大家好,我是若川.持续组织了6个月源码共读活动,感兴趣的可以点此加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步.同时极力推荐订阅我写的<学习源码整体架构系列& ...
最新文章
- C语言实现bmp图像锐化
- java 启动 jetty_如何通过命令行启动或者关闭 Jetty 服务器
- 【深度学习】深度学习安防的探索与实践
- 深度学习分布式策略优化、显存优化、通信优化、编译优化综述
- 鲶鱼效应:为什么要适当的贷款?
- qt弹框输入密码_Android仿支付宝密码输入框
- unity3d 取锚点位置_周三手机课实时共享位置,方便朋友找到见面地点
- openstack租户管理_几大OpenStack的精华问答 | OpenStack都有哪些基础服务?
- 众元教育H3CSE20200603班-IPsec
- 智慧校园供水系统智能管理
- 金融计量学实验报告一
- html怎么绘制中国地图,利用d3.js绘制中国地图
- 建筑企业资质分立风险
- linux cp命令复制整个文件夹
- Win10修改登陆密码
- xxxxxlllllxl的专栏 链接,很多实际动手操作的东西
- 图表插件 - chart.js (柱状图) 学习总结
- win10 更新后蓝牙无法连接以前设备
- 山东大学软件学院项目实训第二周
- 透明网关配置修改后服务器要重启吗,透明网关配置修改后服务器要重启吗