欢迎转载,转载请注明:http://blog.csdn.net/zhgxhuaa


一个Binder实例

我们Binder的学习将从以下的一个实例開始。依据Android文档中的描写叙述,创建一个Binder服务主要包含例如以下3步:

以下详细看一下在eclipse中是怎样开发一个Binder应用的。

第一步:在project文件夹下定义aidl文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.zxh.ipc;
 
import com.zxh.ipc.PermissionInfo;
 
interface ITestManager{
    int checkPermission(String
permName, String pkgName);
     
    int checkUidPermission(String
permName, 
int uid);
     
    boolean addPermission(in
PermissionInfo info);
     
    void removePermission(String
name);
 
    boolean isProtectedBroadcast(String
actionName);
}

第二步:在定义aidl后,eclipse在project文件夹的gen文件夹下会自己主动生成相应的接口,以下是有aidl自己主动生成的Java代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package com.zxh.ipc;
  
public interface ITestManager extends android.os.IInterface
{
    /**
Local-side IPC implementation stub class. */
    public static abstract class Stub extends android.os.Binder implements com.zxh.ipc.ITestManager
    {
        private static final java.lang.String
DESCRIPTOR = 
"com.zxh.ipc.ITestManager";
  
        /**
Construct the stub at attach it to the interface. */
        public Stub()
        {
            this.attachInterface(this,
DESCRIPTOR);
        }
  
        /**
         *
Cast an IBinder object into an com.zxh.ipc.ITestManager interface, generating a proxy if needed.
         */
        public static com.zxh.ipc.ITestManager
asInterface(android.os.IBinder obj)
        {
            if ((obj
== 
null))
{
                return null;
            }
            android.os.IInterface
iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin
!= 
null)
&& (iin 
instanceof com.zxh.ipc.ITestManager)))
{
                return ((com.zxh.ipc.ITestManager)
iin);
            }
            return new com.zxh.ipc.ITestManager.Stub.Proxy(obj);
        }
  
        @Override
        public android.os.IBinder
asBinder()
        {
            return this;
        }
  
        @Override
        public boolean onTransact(int code,
android.os.Parcel data, android.os.Parcel reply, 
int flags)
                throws android.os.RemoteException
        {
            switch (code)
            {
                case INTERFACE_TRANSACTION:
{
                    reply.writeString(DESCRIPTOR);
                    return true;
                }
                case TRANSACTION_checkPermission:
{
                    data.enforceInterface(DESCRIPTOR);
                    java.lang.String
_arg0;
                    _arg0
= data.readString();
                    java.lang.String
_arg1;
                    _arg1
= data.readString();
                    int _result
this.checkPermission(_arg0,
_arg1);
                    reply.writeNoException();
                    reply.writeInt(_result);
                    return true;
                }
                case TRANSACTION_checkUidPermission:
{
                    data.enforceInterface(DESCRIPTOR);
                    java.lang.String
_arg0;
                    _arg0
= data.readString();
                    int _arg1;
                    _arg1
= data.readInt();
                    int _result
this.checkUidPermission(_arg0,
_arg1);
                    reply.writeNoException();
                    reply.writeInt(_result);
                    return true;
                }
                case TRANSACTION_addPermission:
{
                    data.enforceInterface(DESCRIPTOR);
                    com.zxh.ipc.PermissionInfo
_arg0;
                    if ((0 !=
data.readInt())) {
                        _arg0
= com.zxh.ipc.PermissionInfo.CREATOR.createFromParcel(data);
                    }
                    else {
                        _arg0
null;
                    }
                    boolean _result
this.addPermission(_arg0);
                    reply.writeNoException();
                    reply.writeInt(((_result)
? (
1)
: (
0)));
                    return true;
                }
                case TRANSACTION_removePermission:
{
                    data.enforceInterface(DESCRIPTOR);
                    java.lang.String
_arg0;
                    _arg0
= data.readString();
                    this.removePermission(_arg0);
                    reply.writeNoException();
                    return true;
                }
                case TRANSACTION_isProtectedBroadcast:
{
                    data.enforceInterface(DESCRIPTOR);
                    java.lang.String
_arg0;
                    _arg0
= data.readString();
                    boolean _result
this.isProtectedBroadcast(_arg0);
                    reply.writeNoException();
                    reply.writeInt(((_result)
? (
1)
: (
0)));
                    return true;
                }
            }
            return super.onTransact(code,
data, reply, flags);
        }
  
        private static class Proxy implements com.zxh.ipc.ITestManager
        {
            private android.os.IBinder
mRemote;
  
            Proxy(android.os.IBinder
remote)
            {
                mRemote
= remote;
            }
  
            @Override
            public android.os.IBinder
asBinder()
            {
                return mRemote;
            }
  
            public java.lang.String
getInterfaceDescriptor()
            {
                return DESCRIPTOR;
            }
  
            @Override
            public int checkPermission(java.lang.String
permName, java.lang.String pkgName)
                    throws android.os.RemoteException
            {
                android.os.Parcel
_data = android.os.Parcel.obtain();
                android.os.Parcel
_reply = android.os.Parcel.obtain();
                int _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeString(permName);
                    _data.writeString(pkgName);
                    mRemote.transact(Stub.TRANSACTION_checkPermission,
_data, _reply, 
0);
                    _reply.readException();
                    _result
= _reply.readInt();
                finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
  
            @Override
            public int checkUidPermission(java.lang.String
permName, 
int uid) throws android.os.RemoteException
            {
                android.os.Parcel
_data = android.os.Parcel.obtain();
                android.os.Parcel
_reply = android.os.Parcel.obtain();
                int _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeString(permName);
                    _data.writeInt(uid);
                    mRemote.transact(Stub.TRANSACTION_checkUidPermission,
_data, _reply, 
0);
                    _reply.readException();
                    _result
= _reply.readInt();
                finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
  
            @Override
            public boolean addPermission(com.zxh.ipc.PermissionInfo
info) 
throws android.os.RemoteException
            {
                android.os.Parcel
_data = android.os.Parcel.obtain();
                android.os.Parcel
_reply = android.os.Parcel.obtain();
                boolean _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    if ((info
!= 
null))
{
                        _data.writeInt(1);
                        info.writeToParcel(_data, 0);
                    }
                    else {
                        _data.writeInt(0);
                    }
                    mRemote.transact(Stub.TRANSACTION_addPermission,
_data, _reply, 
0);
                    _reply.readException();
                    _result
= (
0 !=
_reply.readInt());
                finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
  
            @Override
            public void removePermission(java.lang.String
name) 
throws android.os.RemoteException
            {
                android.os.Parcel
_data = android.os.Parcel.obtain();
                android.os.Parcel
_reply = android.os.Parcel.obtain();
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeString(name);
                    mRemote.transact(Stub.TRANSACTION_removePermission,
_data, _reply, 
0);
                    _reply.readException();
                finally {
                    _reply.recycle();
                    _data.recycle();
                }
            }
  
            @Override
            public boolean isProtectedBroadcast(java.lang.String
actionName) 
throws android.os.RemoteException
            {
                android.os.Parcel
_data = android.os.Parcel.obtain();
                android.os.Parcel
_reply = android.os.Parcel.obtain();
                boolean _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeString(actionName);
                    mRemote.transact(Stub.TRANSACTION_isProtectedBroadcast,
_data, _reply, 
0);
                    _reply.readException();
                    _result
= (
0 !=
_reply.readInt());
                finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
        }
  
        static final int TRANSACTION_checkPermission
= (android.os.IBinder.FIRST_CALL_TRANSACTION + 
0);
        static final int TRANSACTION_checkUidPermission
= (android.os.IBinder.FIRST_CALL_TRANSACTION + 
1);
        static final int TRANSACTION_addPermission
= (android.os.IBinder.FIRST_CALL_TRANSACTION + 
2);
        static final int TRANSACTION_removePermission
= (android.os.IBinder.FIRST_CALL_TRANSACTION + 
3);
        static final int TRANSACTION_isProtectedBroadcast
= (android.os.IBinder.FIRST_CALL_TRANSACTION + 
4);
    }
  
    public int checkPermission(java.lang.String
permName, java.lang.String pkgName) 
throws android.os.RemoteException;
  
    public int checkUidPermission(java.lang.String
permName, 
int uid) throws android.os.RemoteException;
  
    public boolean addPermission(com.zxh.ipc.PermissionInfo
info) 
throws android.os.RemoteException;
  
    public void removePermission(java.lang.String
name) 
throws android.os.RemoteException;
  
    public boolean isProtectedBroadcast(java.lang.String
actionName) 
throws android.os.RemoteException;
}

第三步:继承上一步生成的接口,实现自己的Service类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.zxh.server;
 
import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.zxh.ipc.ITestManager;
 
import com.zxh.ipc.PermissionInfo;
public class TestService extends Service{
    private final static String
TAG = 
"zxh";
 
    class TestManagerService extends ITestManager.Stub{
         
        @Override
        public int checkPermission(String
permName, String pkgName)
                throws RemoteException
{
            Log.i(TAG, "checkPermission
server"
);
            return 0;
        }
 
        @Override
        public int checkUidPermission(String
permName, 
int uid)
                throws RemoteException
{
            Log.i(TAG, "checkUidPermission
server"
);
            return 0;
        }
 
        @Override
        public boolean addPermission(PermissionInfo
info) 
throws RemoteException
{
            Log.i(TAG, "addPermission
server"
);
            return false;
        }
 
        @Override
        public void removePermission(String
name) 
throws RemoteException
{
            Log.i(TAG, "removePermission
server"
);
        }
 
 
        @Override
        public boolean isProtectedBroadcast(String
actionName)
                throws RemoteException
{
            Log.i(TAG, "isProtectedBroadcast
server"
);
            return false;
        }
    }
     
     
    private TestManagerService
mService = 
new TestManagerService();
     
    @Override
    public IBinder
onBind(Intent intent) {
        Log.i("zxh""unbindService");
        return mService;
    }
     
    @Override
    public void unbindService(ServiceConnection
conn) {
        super.unbindService(conn);
        Log.i("zxh""unbindService");
    }
}

第四步:实现client代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.zxh.server;
 
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
 
import com.zxh.ipc.ITestManager;
 
public class MainActivity extends Activity
{
 
    private ITestManager
manager = 
null;
     
    ServiceConnection
connection = 
new ServiceConnection()
{
        @Override
        public void onServiceDisconnected(ComponentName
name) {
            Log.i("binder""onServiceDisconnected");
        }
         
        @Override
        public void onServiceConnected(ComponentName
name, IBinder service) {
            manager
= ITestManager.Stub.asInterface(service);
        }
    };
     
    @Override
    protected void onCreate(Bundle
savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.startServer).setOnClickListener(new OnClickListener()
{
            @Override
            public void onClick(View
v) {
                bindService(new Intent(MainActivity.this,
TestService.
class),
connection, Service.BIND_AUTO_CREATE);
            }
        });
         
        findViewById(R.id.stop).setOnClickListener(new OnClickListener()
{
            @Override
            public void onClick(View
v) {
                unbindService(connection);
            }
        });
         
        findViewById(R.id.check).setOnClickListener(new OnClickListener()
{
            @Override
            public void onClick(View
v) {
                try {
                    manager.checkPermission("permName""pkgName");
                catch (RemoteException
e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

到这里我们就实现了一个完整的Binder实例,以下是project文件夹的截图:

完整代码能够查看后面的附件。以下来介绍一下这个实例中涉及到的一些知识点。

AIDL

除了eclipse,也能够使用Android开发包中提供的aidl命令工具来生成,例如以下是adil命令:

关于adil的具体介绍能够查看Android官方文档,地址为:http://developer.android.com/intl/zh-cn/guide/components/aidl.html

想要了解aidl处理过程的朋友也能够自己查看aidl的源码,位于@/frameworks/base/tools/adil。

AIDL编译产生的类

以下我们来分析一下aidl编译产生的ITestManager类。

从ITestManager中能够看出,ITestManager实现了IInterface接口。在ITestManager类中共包括了三部分内容,各自是:

  • 我们在ITestManager.adil中定义的接口。

  • Stub类:主要由Server端实现,Server端通过继承本类,来提供详细的处理逻辑。

  • Proxy类:client代理,通过mRemote成员变量訪问远程Binder服务。

为了实现我们在ITestManager自定义接口的跨进程通信,Stub类和Proxy都实现了ITestManager接口。Stub自己继承了Binder类来实现Binder机制,Proxy则以引用的方式实现Binder机制。

client和服务端的通信主要通过onTransact方法实现,client和服务端的数据传递通过Parcel类完毕。这里须要注意一个问题:就是在client写入数据的顺序与在服务端读取数据的顺序必须是一致的。

尽管在上面的实现中,我们定义了一个Service类TestService,但这里要说明的是Service甚至adil都不是必须的,使用者全然能够自定义。

自顶向下分析Binder【1】—— Binder实例篇的更多相关文章

  1. [Android进阶]Binder学习(初始篇)

    Android中Binder学习(初始篇) 本篇博客学习自侯亮的博客.地址为: 红茶一杯话Binder 1 什么是Binder? 简单地说.Binder是Android平台上的一种跨进程交互技术. 该 ...

  2. 红茶一杯话Binder (传输机制篇_下)

    红茶一杯话Binder (传输机制篇_下) 侯 亮 1 事务的传递和处理 从IPCThreadState的角度看,它的transact()函数是通过向binder驱动发出BC_TRANSACTION语 ...

  3. 红茶一杯话Binder (传输机制篇_中)

    红茶一杯话Binder (传输机制篇_中) 侯 亮 1 谈谈底层IPC机制吧 在上一篇文章的最后,我们说到BpBinder将数据发到了Binder驱动.然而在驱动层,这部分数据又是如何传递到BBind ...

  4. 红茶一杯话Binder(传输机制篇_上)

    红茶一杯话Binder (传输机制篇_上) 侯 亮 1 Binder是如何做到精确打击的? 我们先问一个问题,binder机制到底是如何从代理对象找到其对应的binder实体呢?难道它有某种制导装置吗 ...

  5. Andorid Binder进程间通信---Binder本地对象,实体对象,引用对象,代理对象的引用计数

    本文參考<Android系统源码情景分析>,作者罗升阳. 一.Binder库(libbinder)代码: ~/Android/frameworks/base/libs/binder --- ...

  6. [置顶] Cocos2d-x 实例源码分析之二 小实例的主框架

    这篇文章是分析第一个小实例ActionTest的源码.其实所有实例程序的结构都是一样的,只有特定方法里的代码不同,大的框架都是一样的.也就是说看完这篇文章你就可以自己开始分析其他源码了. 废话不多说, ...

  7. 一步步实现windows版ijkplayer系列文章之二——Ijkplayer播放器源码分析之音视频输出——视频篇

    一步步实现windows版ijkplayer系列文章之一--Windows10平台编译ffmpeg 4.0.2,生成ffplay 一步步实现windows版ijkplayer系列文章之二--Ijkpl ...

  8. ASP.NET MVC 4 插件化架构简单实现-实例篇

    先回顾一下上篇决定的做法: 1.定义程序集搜索目录(临时目录). 2.将要使用的各种程序集(插件)复制到该目录. 3.加载临时目录中的程序集. 4.定义模板引擎的搜索路径. 5.在模板引擎的查找页面方 ...

  9. MVC 4 插件化架构简单实现实例篇

    ASP.NET MVC 4 插件化架构简单实现-实例篇   先回顾一下上篇决定的做法: 1.定义程序集搜索目录(临时目录). 2.将要使用的各种程序集(插件)复制到该目录. 3.加载临时目录中的程序集 ...

  10. Asp.Net MVC2.0 Url 路由入门---实例篇

    本篇主要讲述Routing组件的作用,以及举几个实例来学习Asp.Net MVC2.0 Url路由技术. 接着上一篇开始讲,我们在Global.asax中注册一条路由后,我们的请求是怎么转到相应的Vi ...

随机推荐

  1. 如何删除JAVA集合中的元素

    经常我们要删除集合中的某些元素.有些可能会这么写. public void operate(List list){ for (Iterator it = list.iterator(); it.has ...

  2. tomcat加载时报The web application [/dmscs] created a ThreadLocal with key of type

    严重: The web application [/dmscs] created a ThreadLocal with key of type [com.opensymphony.xwork2.inj ...

  3. 64位win7旗舰版搭建apache+php+mysql开发环境[转]

      我建议把apache.php.mysql都安装在一个文件夹中,比如:web/apache.web/php.web/mysql 1.安装apache2.2.25,请查看win7下安装VC9版本的ap ...

  4. [置顶] gis海量资源网盘提供VIP账号无广告高速下载 (更新更多资源)

    资源网盘下载地址:http://laoheitan.bego.cc/ 城通网盘 vip帐号共享 省去 烦人的 广告  多任务同时下载 独乐乐 不如众乐乐 好人 勿改密码. 获取到 vip下载连接后 请 ...

  5. 《Head First 设计模式》学习笔记——状态模式

    在软件开发过程中.应用程序可能会依据不同的情况作出不同的处理. 最直接的解决方式是将这些全部可能发生的情况全都考虑到.然后使用if... ellse语句来做状态推断来进行不同情况的处理. 可是对复杂状 ...

  6. ubuntu 13.10 Rhythmbox不能播放mp3 和中文乱码的问题

    1.ubuntu 13.10 Rhythmbox不能播放mp3的解决方法 软件中心搜索(ubuntu额外的版权受限软件)不带括号 2.中文乱码问题解决方法: 终端顺序操作 : 1.  sudo ged ...

  7. HTTP协议的请求和响应学习

    本篇作为学习servlet的前提,http协议是学习JavaWeb开发的基石,不深入了解http协议,就不能说掌握了JavaWeb开发. HTTP协议有两个版本:HTTP1.0和HTTP1.1,那么有 ...

  8. Beauty of Array

    Description Edward has an array A with N integers. He defines the beauty of an array as the summatio ...

  9. Servlet过滤器——创建过滤器

    1.概述 介绍如何创建一个过滤器,并使用过滤器在打开页面的同时输出信息,此功能是由过滤器处理完成的. 2.技术要点 Serlvet过滤器实现了Filter接口,在Filter接口中定义了以下几个方法: ...

  10. HOOK自绘原理 good

    做“HOOK文件打开/保存对话框”的过程中,我首先研究了界面库的相关知识.界面库一般都是由C/C++这种中低级语言编码,这是因为在Windows下的界面库实现技术大都以直接操作控制Windows的消息 ...