Service官方教程(7)Bound Service示例之1-同进程下直接继承Service
Extending the Binder class
If your service is used only by the local application and does not need to work across processes, then you can implement your own Binder
class that provides your client direct access to public methods in the service.
Note: This works only if the client and service are in the same application and process, which is most common. For example, this would work well for a music application that needs to bind an activity to its own service that's playing music in the background.
Here's how to set it up:步骤如下
- In your service, create an instance of
Binder
that either:- contains public methods that the client can call
- returns the current
Service
instance, which has public methods the client can call - or, returns an instance of another class hosted by the service with public methods the client can call
- Return this instance of
Binder
from theonBind()
callback method. - In the client, receive the
Binder
from theonServiceConnected()
callback method and make calls to the bound service using the methods provided.
Note: The reason the service and client must be in the same application is so the client can cast the returned object and properly call its APIs. The service and client must also be in the same process, because this technique does not perform any marshalling across processes.
For example, here's a service that provides clients access to methods in the service through a Binder
implementation:
1 public class LocalService extends Service { 2 3 // Binder given to clients 4 private final IBinder mBinder = new LocalBinder(); 5 6 // Random number generator 7 private final Random mGenerator = new Random(); 8 9 /** 10 * Class used for the client Binder. Because we know this service always 11 * runs in the same process as its clients, we don't need to deal with IPC. 12 */ 13 public class LocalBinder extends Binder { 14 LocalService getService() { 15 // Return this instance of LocalService so clients can call public methods 16 return LocalService.this; 17 } 18 } 19 20 @Override 21 public IBinder onBind(Intent intent) { 22 return mBinder; 23 } 24 25 /** method for clients */ 26 public int getRandomNumber() { 27 return mGenerator.nextInt(100); 28 } 29 }
The LocalBinder
provides the getService()
method for clients to retrieve the current instance of LocalService
. This allows clients to call public methods in the service. For example, clients can call getRandomNumber()
from the service.
Here's an activity that binds to LocalService
and calls getRandomNumber()
when a button is clicked:
1 public class BindingActivity extends Activity { 2 3 LocalService mService; 4 boolean mBound = false; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_binding); 10 } 11 12 @Override 13 protected void onStart() { 14 super.onStart(); 15 16 // Bind to LocalService 17 Intent intent = new Intent(this, LocalService.class); 18 bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 19 } 20 21 @Override 22 protected void onStop() { 23 super.onStop(); 24 // Unbind from the service 25 if (mBound) { 26 unbindService(mConnection); 27 mBound = false; 28 } 29 } 30 31 /** Called when a button is clicked (the button in the layout file attaches to 32 * this method with the android:onClick attribute) */ 33 public void onButtonClick(View v) { 34 if (mBound) { 35 // Call a method from the LocalService. 36 // However, if this call were something that might hang, then this request should 37 // occur in a separate thread to avoid slowing down the activity performance. 38 int num = mService.getRandomNumber(); 39 Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show(); 40 } 41 } 42 43 /** Defines callbacks for service binding, passed to bindService() */ 44 private ServiceConnection mConnection = new ServiceConnection() { 45 46 @Override 47 public void onServiceConnected(ComponentName className, 48 IBinder service) { 49 // We've bound to LocalService, cast the IBinder and get LocalService instance 50 LocalService.LocalBinder binder = (LocalService.LocalBinder) service; 51 mService = binder.getService(); 52 mBound = true; 53 } 54 55 @Override 56 public void onServiceDisconnected(ComponentName arg0) { 57 mBound = false; 58 } 59 }; 60 }
The above sample shows how the client binds to the service using an implementation of ServiceConnection
and the onServiceConnected()
callback. The next section provides more information about this process of binding to the service.
Note: In the example above, the onStop()
method unbinds the client from the service. Clients should unbind from services at appropriate times, as discussed in Additional Notes.
For more sample code, see the LocalService.java
class and the LocalServiceActivities.java
class in ApiDemos.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
2015-09-23 Drawable(2)State list Drawable Resource介绍
2015-09-23 Drawable(1)各种Drawable Resource介绍