Develop系列-API Guides-应用组件-Services-Bound Services
2014-08-19 23:15
387 查看
Bound Services
CS架构,其中C是调用组件,S是Bound Services;C通过bindService来绑定,这个方法立即返回,没有返回值,C需要实现ServiceConnection里面的onServiceConnected和onServiceDisconnected接口。
多个C绑定同一个S时,S只调用一次onBind返回IBinder,后续来绑定S的C,直接得到同一个IBinder,onBind不再重复执行。
创建Bound Services
扩展Binder类:只在应用内部调用的服务,不会被其他应用或者跨进程调用。使用Messenger:Service定义Handler来接收Message,Client发送Message。这是IPC调用最简单的实现方式,但是Messenger队列在一个线程中排队处理所有请求,没法同时多线程处理。
用AIDL:如果是跨进程的并且需要同时处理多个请求,那么请直接使用AIDL
扩展Binder类
Service代码:public class LocalService extends Service { // Binder given to clients private final IBinder mBinder = new LocalBinder(); // Random number generator private final Random mGenerator = new Random(); /** * 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. */ public class LocalBinder extends Binder { LocalService getService() { // Return this instance of LocalService so clients can call public methods return LocalService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } /** method for clients */ public int getRandomNumber() { return mGenerator.nextInt(100); } }
Client代码:
public class BindingActivity extends Activity { LocalService mService; boolean mBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { super.onStart(); // Bind to LocalService Intent intent = new Intent(this, LocalService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (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) */ public void 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() */ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; }
使用Messenger
Service代码:public class MessengerService extends Service { /** Command to the service to display a message */ static final int MSG_SAY_HELLO = 1; /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override public void 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. */ final Messenger mMessenger = new Messenger(new IncomingHandler()); /** * When binding to the service, we return an interface to our messenger * for sending messages to the service. */ @Override public IBinder onBind(Intent intent) { Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show(); return mMessenger.getBinder(); } }
Client代码:
public class ActivityMessenger extends Activity { /** 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. */ private ServiceConnection mConnection = new ServiceConnection() { public void 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 = new Messenger(service); mBound = true; } public void 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; } }; public void sayHello(View v) { if (!mBound) return; // Create and send a message to the service, using a supported 'what' value Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0); try { mService.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { super.onStart(); // Bind to the service bindService(new Intent(this, MessengerService.class), mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } }
绑定服务
只有activities、Services、content providers能绑定到服务,broadcast receiver不能绑定!生命周期
相关文章推荐
- Develop系列-API Guides-应用组件-Services-AIDL
- Develop系列-API Guides-应用组件-Services
- Develop系列-API Guides-应用组件-Activities-Tasks and Back Stack
- Develop系列-API Guides-应用组件-Intents and Intent Filters
- Develop系列-API Guides-应用组件-Activities-Loaders
- Develop系列-API Guides-应用组件-Activities
- Develop系列-API Guides-简介-系统权限
- Silverlight 4 + RIA Services之商业应用系列----7 使用RIA Service Class Library
- Silverlight 4 + RIA Services之商业应用系列----9.2 MVVM+RIA Service+CRUD
- 开源组件应用系列:Log4net之基本配置
- Silverlight 4 + RIA Services之商业应用系列----8 url重写和友好页面的实现
- Android四大组件应用系列——Activity与Service交互实现APK下载
- Android API Guides 之 App Components(8) - Services - Bound Services
- Develop系列-API Guides-简介-设备兼容性
- Android四大组件应用系列——实现电话拦截和电话录音
- Silverlight 4 + RIA Services之商业应用系列----1 使用RIA Services
- Vaadin系列(二) 应用开发:Table 组件
- Silverlight 4 + RIA Services之商业应用系列
- Sencha touch 开发系列:移动应用开发之组件
- Silverlight 4 + RIA Services之商业应用系列 6----Domain Service的数据格式和自定义方法