android AIDL实现详解
来源:互联网 发布:background url 知乎 编辑:程序博客网 时间:2024/04/28 21:07
AIDL接口描述语言,在android中用来实现IPC非常方便。
一.服务端
1.在工程A中是实现AIDL文件IMyService.aidl,写法无误会在gen目录下自动生成IMyService.java
package com.jyc.aidl.demo;interface IMyService{String getValue(String key);}
2.创建Service,onBind()函数需要返回IMyService.Stub对象,AIDL中定义的函数在Stub中实现,最后在AndroidMainifest.xml中注册此Service,需要定义此Service的action,这样客户端才能用Intent来绑定此Service。
package com.jyc.demo.outmode;import com.jyc.aidl.demo.IMyService;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.RemoteException;public class MyService extends Service {int i =0;@Overridepublic IBinder onBind(Intent arg0) {return new IMyService.Stub(){@Overridepublic String getValue(String key) throws RemoteException {i++;return "from service:"+i;}};}}
二.客户端
1.拷贝服务端中gen下面由aidl自动生成的java文件(连带包路径一起)至客户端的src中,这样才可以调用服务端的接口
2.用bindServiced的方式启动service代码如下
package com.jyc.aidl.client.demo;import com.jyc.aidl.demo.IMyService;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.view.View;import android.widget.Button;public class AIDLClientActivity extends Activity {private Button but; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); bindMyService(); but = (Button)findViewById(R.id.button1); but.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {try {but.setText(myService.getValue("aa"));} catch (RemoteException e) {e.printStackTrace();}}}); } private void bindMyService(){ this.bindService(new Intent("com.jyc.MYSERVICE.AIDL"), conn, Context.BIND_AUTO_CREATE); } IMyService myService = null; ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {myService = null;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {myService = IMyService.Stub.asInterface(service);}};}
工程下载地址:
http://download.csdn.net/detail/jiang4920/4697723
- android AIDL实现详解
- Android进阶:AIDL实现IPC使用详解
- 什么是aidl?Android AIDL详解
- 什么是aidl?Android AIDL详解
- 什么是aidl?Android AIDL详解
- Android AIDL使用详解
- Android AIDL详解_1
- Android AIDL详解_2
- Android AIDL使用详解
- Android AIDL使用详解
- Android AIDL使用详解
- Android AIDL使用详解
- Android AIDL使用详解
- Android AIDL使用详解
- Android AIDL使用详解
- Android AIDL使用详解
- Android AIDL使用详解
- Android AIDL使用详解 .
- 重力传感器代码分析
- android和RTSP视频文件播放(一)
- SSH中的web.xml配置文件格式
- TableView详细解释
- mfc 中在对Gdi+ 进行配置之后,产生的error错误。如下:
- android AIDL实现详解
- [原创]vc++实现删除httponly cookie
- vim 删除每行开头结尾空格
- IOS CoreData 多表查询(下)
- SQL SERVER转换到ORACLE应注意的几点问题
- 指针小结
- [Android] 将Android工程做成jar包和资源文件
- 一地的凄凉、写满了你赐予的悲伤
- ortp 编译测试