Android开发中,Binder是一种跨进程通信方式,而使用AIDL可以实现Binder的工作。

如何使用它是了解它的第一步,本文章主要记录使用Binder的一些步骤。(代码思路参考《Android开发艺术探索》任玉刚 著)

1.创建两个activity

两个activity(OneActivity、TwoActivity),将OneActivity假设为服务端,TwoActivity假设为客户端,分别运行在不同进程中

在AndroidManifest.xml中,为TwoActivity设置进程,这样两个activity就分别运行在不同的进程中了

<activity android:name=".TwoActivity" android:process=":test"/>

2. 创建AIDL文件

在AIDL文件中声明客户端想要调用服务端的方法

interface IInfManager {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void setName(String name); String getName();
}

AIDL文件声明完,activity等文件并不能调用到IInfManager接口,需要在app的build.gradle文件中的android{}中添加

sourceSets{
main{
java.srcDirs = ['src/main/java', 'src/main/aidl']
}
}

然后点击sync now按钮,activity文件就可以调用到IInfManager接口了,可以在app\build\generated\source\aidl\debug文件下找到自动生成的IInfManager.java文件。

3.创建Service

Service中创建Binder对象,在onBind方法中返回这个对象,Binder对象中具体实现了IInfManager接口中的方法。Service需要在AndroidManifest.xml中注册。

public class InfManageService extends Service{

    private String name;

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {
name = intent.getStringExtra("name");
return super.onStartCommand(intent, flags, startId);
} @Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
} private Binder binder = new IInfManager.Stub() {
@Override
public void setName(String mName) throws RemoteException {
name = mName;
} @Override
public String getName() throws RemoteException {
return name;
}
};
}

4.服务端OneActivity

OneActivity中设置按钮跳转至TwoActivity,这里为了简单,使用startService可以为InfManageService中name变量初始化"zhangsan"的值。也可以与客户端TwoActivity中一样,绑定service,建立连接,来设置name的值(具体参考下一步客户端的用法)。

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one); Intent intent = new Intent(OneActivity.this, InfManageService.class);
intent.putExtra("name", "zhangsan");
startService(intent); btn_one_gototwo = (Button) findViewById(R.id.btn_one_gototwo); btn_one_gototwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(OneActivity.this, TwoActivity.class);
startActivity(intent);
}
});
}

5.客户端TwoActivity

首先绑定InfManageService服务,建立连接,连接成功后通过返回的IBinder对象可以获得IInfManager接口,可以通过这个接口去使用服务端的方法。

private TextView tv_two_name;
private Button btn_two_change; private IInfManager iInfManager; private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iInfManager = IInfManager.Stub.asInterface(service);
try {
tv_two_name.setText(iInfManager.getName());
Log.i("TwoActivity","first:" + iInfManager.getName());
iInfManager.setName("lisi");
Log.i("TwoActivity","next:" + iInfManager.getName());
}catch (RemoteException e){ }
} @Override
public void onServiceDisconnected(ComponentName name) { }
}; @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two); tv_two_name = (TextView) findViewById(R.id.tv_two_name);
btn_two_change = (Button) findViewById(R.id.btn_two_change); Intent intent = new Intent(TwoActivity.this, InfManageService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE); btn_two_change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
iInfManager.setName("wangmazi");
tv_two_name.setText(iInfManager.getName());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
} @Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}

上面代码onServiceConnected方法中,首先在TwoActivity界面中显示了服务端的name变量内容"zhangsan"

Binder基本使用的更多相关文章

  1. 笔记:Binder通信机制

    TODO: 待修正 Binder简介 Binder是android系统中实现的一种高效的IPC机制,平常接触到的各种XxxManager,以及绑定Service时都在使用它进行跨进程操作. 它的实现基 ...

  2. Binder in Java

    Android在Native层实现了进程间的Binder通信,但是上层应用程序的开发及Framework的实现都是Java,用Java层再实现一次肯定是不合理的,Java可以通过JNI调用Native ...

  3. Binder In Native

    关于Binder的设计思想与Driver层实现细节可以看这个:Android Binder设计与实现 - 设计篇,这里首先简要概括一下. Service的每个Binder实体位于Service所属的进 ...

  4. [转]Android Binder设计与实现 - 设计篇

    摘要 Binder是Android系统进程间通信(IPC)方式之一.Linux已经拥有管道,system V IPC,socket等IPC手段,却还要倚赖Binder来实现进程间通信,说明Binder ...

  5. 用C++开发Binder服务

    用C++来实现Binder服务比较麻烦,原因是没有AIDL的辅助,必须手工来写中间的代码. 首先写一个服务类ExampleServer的代码: class ExampleServer : public ...

  6. C++实例讲解Binder通信

    binder是android里面的通信机制,这就不说它如何如何好了,Goog已经说过了,这里不多说.binder是一个面向对象的编程方法,大量使用虚函数类.最近研究binder看到一网友写的,就借鉴一 ...

  7. 为什么使用Binder而不是其他IPC机制

    本文搬运自:Advantages of using Binder for IPC in Android 使用Binder而不是其他(Semaphores , Message Queue, PIPES) ...

  8. C++使用binder实例

    Android系统最常见也是初学者最难搞明白的就是Binder了,很多很多的Service就是通过Binder机制来和客户端通讯交互的.所以搞明白Binder的话,在很大程度上就能理解程序运行的流程. ...

  9. LocalBroadcastManager 的实现原理,Handler还是 Binder?

    原文: http://www.trinea.cn/android/localbroadcastmanager-impl/ 对 LocalBroadcastManager 大家应该都不陌生,相对 Bro ...

  10. 浅谈android binder机制

    binder机制 是谷歌优化在android上更适合终端的IPC(多进程通信方式),满足系统对通信方式,传输性能和安全性的要求. 特性: 1. 用驱动程序来推进进程间的通信.2. 通过共享内存来提高性 ...

随机推荐

  1. 美食家app开发日记

    民以食为天. 作为一个20年几乎没做过饭的吃货,从这个假期开始,想利用些时间,自己动手尝试,做些好吃的出来,一方面给父母减轻点负担,获得点成就感,一方面体验生活,学学厨艺,感受生活的乐趣和美好,其三, ...

  2. 9、python判断语句与循环语句

    前言:本文主要介绍python判断语句与循环语句,包括if语句.while循环.for循环.range函数. 一.if语句  关键字:if.elif.else,写法如下: # if if 条件: # ...

  3. 解决 C# GetPixel 和 SetPixel 效率问题(转)

    在对Bitmap图片操作的时候,有时需要用到获取或设置像素颜色方法:GetPixel 和 SetPixel, 如果直接对这两个方法进行操作的话速度很慢,这里我们可以通过把数据提取出来操作,然后操作完在 ...

  4. http1.0、http1.x、http 2和https梳理

    http1.0.http1.x.http 2和https梳理 Http1.x 线程阻塞,在同一时间,同一域名的请求有一定数量限制,超过限制数目的请求会被阻塞 http1.0 缺陷:浏览器与服务器只保持 ...

  5. 小白学 Python 数据分析(1):数据分析基础

    各位同学好,小编接下来为大家分享一些有关 Python 数据分析方面的内容,希望大家能够喜欢. 人工植入广告: PS:小编最近两天偷了点懒,好久没有发原创了,最近是在 CSDN 开通了一个付费专栏,用 ...

  6. [C语言学习笔记二] extern 函数的用法

    extern 用来定义一个或多个变量.其后跟数据类型名和初始值.例如: extern int a =10 它与 int,long long int,double,char的本质区别,在于 extern ...

  7. 读《Clean Code 代码整洁之道》之感悟

    盲目自信,自认为已经敲了几年代码,还看什么整洁之道啊.我那可爱的书架读懂了我的心思,很明事理的保护起来这本小可爱,未曾让它与我牵手 最近项目中的 bug 有点多,改动代码十分吃力,每看一行代码都带一句 ...

  8. 机器学习:没有免费午餐定理(No Free Lunch Theorem)

    思考 机器学习中哪个算法好?哪个算法差呢? 下面两条线,哪个更好呢? 没有免费午餐定理 如果我们不对特征空间有先验假设,则所有算法的平均表现是一样的. 假设我们的计算机只有两个存储单元,而且每个存储单 ...

  9. Kubernetes学习(二)

    二 POD生命周期 initC作用说明 initC举例说明 init-pod.yaml apiVersion: v1kind: Podmetadata: name: myapp-pod labels: ...

  10. Web 开发工具类(2): HttpClientUtils

    HttpClientUtils 整合了一些 web开发中常用的httpClient操作: package com.evan.common.utils; import java.io.IOExcepti ...