首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

关于AIDL的入门札记

2013-10-31 
关于AIDL的入门笔记package com.example.hahainterface IDownService {//这里不需要加权限修饰符(就如pub

关于AIDL的入门笔记
package com.example.haha; interface IDownService { //这里不需要加权限修饰符(就如public.private之类的) void downLoad(String path); }

?

?

? ?很明显这是一个接口,如果您是用eclipse的话,它会在gen里面自动生成一个IDownService.java文件。

? ? 然后实现这个接口,让其他地方通过接口来调用这个实现的方法

?

?

package com.example.aidl;import com.example.haha.IDownService;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.RemoteException;import android.util.Log;/** * @author cfuture_小智 * @Description 远程服务接口的实现 */public class DownService extends Service {        //这里为什么是new 一个Stub我也不太清楚private IDownService.Stub binder = new IDownService.Stub() {@Overridepublic void downLoad(String path) throws RemoteException {Log.v("AIDL", this.getClass().getName()+ "---downRemoteException:++path" + path);}};//在远程调用的时候,将会得到binder(事实它是IDownService的实现)这个对象@Overridepublic IBinder onBind(Intent intent) {return binder;}}

?最后在AndroidManifest.xml定义一下service,因为你在另一个项目里只能通过隐性Intent打开服务。

        <service android:name="com.example.aidl.DownService" >            <intent-filter>                <action android:name="com.cfuture.xiaozhi.aidltest" />            </intent-filter>        </service>

?

?

到这里服务端的方法都已经做好了。

?

接下来建一个客户端AIDLClient来调用服务端的方法。

当然,你还要把那个AIDL文件,从AIDLService项目中连包一起复制过来。

像图片这样:


关于AIDL的入门札记
?

再写你的调用代码

package com.cfuture.xiaozhi.example.aidlclient;import com.example.haha.IDownService;import android.app.Activity;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.view.Menu;public class MainActivity extends Activity {private IDownService downService;private ServiceConnection serviceConnection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {downService = null;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {                         //在这里就可以得到DownServce的实例了,这时候你想干嘛就干嘛downService = IDownService.Stub.asInterface(service);try {downService.downLoad("http://google.com");} catch (RemoteException e) {e.printStackTrace();}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Intent intent = new Intent("com.cfuture.xiaozhi.aidltest");// 绑定到远程服务bindService(intent, serviceConnection, 1);}}

?OK了,这样子就行了

热点排行