1、为什么要有AIDL?
无论学什么东西,最先得弄明白为什么要有这个东西,不要说存在即是合理,存在肯定合理,但是你还是没有明白。对于AIDL有一些人的浅显概念就是,AIDL可以跨进程访问其他应用程序,和其他应用程序通讯,那我告诉你,很多技术都可以访问,如广播(应用A在 Android Manifest.xml中注册指定Action的广播)应用B发送指定Action的广播,A就能收到信息,这样也能看成不同应用之间完成了通讯(但是这种通讯是单向的);还如ContentProvider,通过URI接口暴露数据给其他应用访问;但是这种都算不上是应用之间的通讯。可能最让人迷惑的是Android推出来了Messager,它就是完成应用之间的通讯的。那么为什么还要有AIDL呢,官方文档介绍AIDL中有这么一句话:1 | Note: if
for
do
interface
if
do
interface
|
2、AIDL使用
第一、定义AIDL文件12345678910111213141516 | // package // /** interface
/** Request the process ID of this service, to do evil things with it. */ int /** Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void
int
long
boolean
float
double
} |
1234567891011121314151617181920212223242526272829303132333435 | package import import
import
import
import public DDService extends
@Override public onCreate() { super .onCreate(); System.out.println( "DDService onCreate........" + "Thread: " + Thread.currentThread().getName()); } @Override public
System.out.println( "DDService onBind" ); return
} private IRemoteService.Stub mBinder = new
public getPid(){ System.out.println( "Thread: " + Thread.currentThread().getName()); System.out.println( "DDService getPid " ); return
} public basicTypes( int
long
boolean
float
double
System.out.println( "Thread: " + Thread.currentThread().getName()); System.out.println( "basicTypes aDouble: " + aDouble + " anInt: " + anInt+ " aBoolean " + aBoolean+ " aString " + aString); } }; } |
这样我们的服务端就完成了,把服务端运行到模拟器(或者手机上),等一会可以看一下打印信息,重点看“线程名”
第三、实现客户端测试代码 新建另一个工程,同样需要添加AIDL协议文件(这是一个标准的协议文件,定义对外服务),这里我列出来我的测试代码:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 | package import
import
import
import
import
import
import
import
import
import import public MainActivity extends
private
@Override public onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); } ServiceConnection conn = new
@Override public onServiceDisconnected(ComponentName name) { } @Override public onServiceConnected(ComponentName name, IBinder service) { remoteService = IRemoteService.Stub.asInterface(service); try
int
int
System.out.println( "currentPID: " + currentPid + " remotePID: " + pid); remoteService.basicTypes( 12 , 1223 , true , 12 .2f, 12.3 , "我们的爱,我明白" ); } catch
e.printStackTrace(); } System.out.println( "bind success! " + remoteService.toString()); } }; /** * 监听按钮点击 * @param view */ public buttonClick(View view) { System.out.println( "begin bindService" ); Intent intent = new
"duanqing.test.aidl" ); bindService(intent, conn, Context.BIND_AUTO_CREATE); } @Override protected onDestroy() { super .onDestroy(); unbindService(conn); } } |