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:步骤如下

  1. 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
  2. Return this instance of Binder from the onBind() callback method.
  3. In the client, receive the Binder from the onServiceConnected() 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:

 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();
}
}

  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:

 public class BindingActivity extends Activity {

     LocalService mService;
boolean mBound = false; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binding);
} @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
LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
mService = binder.getService();
mBound = true;
} @Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}

  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.

Service官方教程(7)Bound Service示例之1-同进程下直接继承Service的更多相关文章

  1. Service官方教程(8)Bound Service示例之2-跨进程使用Messenger

    Compared to AIDL When you need to perform IPC, using a Messenger for your interface is simpler than ...

  2. Service官方教程(6)Bound Services主要用来实现通信服务,以及3种实现通信的方案简介。

    1.Bound Services A bound service is the server in a client-server interface. A bound service allows ...

  3. Service官方教程(3)Bound Services

    Bound Services 1.In this document The Basics Creating a Bound Service Extending the Binder class Usi ...

  4. Service官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信

    Android Interface Definition Language (AIDL) 1.In this document Defining an AIDL Interface Create th ...

  5. Service官方教程(10)Bound Service的生命周期函数

    Managing the Lifecycle of a Bound Service When a service is unbound from all clients, the Android sy ...

  6. Service官方教程(2)*IntentService与Service示例、onStartCommand()3个返回值的含义。

    1.Creating a Started Service A started service is one that another component starts by calling start ...

  7. Service官方教程(1)Started与Bound的区别、要实现的函数、声明service

    Services 简介和分类 A Service is an application component that can perform long-running operations in the ...

  8. Service官方教程(9)绑定服务时的注意事项

    Binding to a Service Application components (clients) can bind to a service by calling bindService() ...

  9. Service官方教程(4)两种Service的生命周期函数

    Managing the Lifecycle of a Service The lifecycle of a service is much simpler than that of an activ ...

随机推荐

  1. 创立一个站点的前前后后(起因,域名,云平台,备案,CDN等等)(1)

    起因 写完<完美软件开发:方法与逻辑>这书后,原本想继续写书的,可出来參加了些社区活动后,我发现我写的书大家评价还行.但事实上不太理解.而接下来想写的书更加抽象点.准备叫<管理的解析 ...

  2. 巧用Drawable 实现Android UI 元素间距效果

    源文地址: 巧用Drawable 实现Android UI 元素间距效果 在大部分的移动UI或者Web UI都是基于网格概念而设计的.这种网格一般都是有一些对其的方块组成,然后它们组合成为一个块.使用 ...

  3. ART虚拟机之Trace原理(转)

    一.概述 Android 6.0系统采用的art虚拟机,所有的Java进程都运行在art之上,当应用发生ANR(Application Not Response,其中最终的一个环节便是向目标进程发送信 ...

  4. Project Euler:Problem 61 Cyclical figurate numbers

    Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygon ...

  5. ZOJ 2859 二维线段树

    思路:自己写的第二发二维线段树1A.哈哈,看来对二维的push操作比較了解了:可是还没遇到在两个线段树中同一时候进行push操作的,事实上这题我是想在x维和y维同一时候进行push操作的.可是想了好久 ...

  6. 【Java集合源代码剖析】HashMap源代码剖析

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/36034955 您好,我正在參加CSDN博文大赛,假设您喜欢我的文章.希望您能帮我投一票.谢 ...

  7. IPython与Jupyter notebook 安装与配置,插件扩展,主题,PDF输出

    基于 python2.7.13 32-bit版本安装 1.安装pyreadline https://pypi.python.org/pypi/pyreadline 下载对应的32位版本 安装Micro ...

  8. mouseout和mouseover、mouseenter和mouseleave

          在前端开发中经常会碰到当鼠标放到一个元素上时会弹出你一个元素,鼠标离开那个弹出元素后隐藏.这类效果一般要用到一些鼠标事件,一类是mouseout和mouseover,另一类是mouseen ...

  9. Highcharts报表——让你的网页上图表画的飞起

    Highcharts是一款纯javascript编写的图表库,能够很简单便捷的在Web网站或Web应用中添加交互性的图表,Highcharts目前支持直线图.曲线图.面积图.柱状图.饼图.散点图等多达 ...

  10. File to byte[] in Java

    File to byte[] in Java - Stack Overflow https://stackoverflow.com/questions/858980/file-to-byte-in-j ...