AIDL初体验
今天刚看了看AIDL,至于什么叫AIDL,网上都有,实现所谓的进程间通信。
也就是client和server进行通信。下面是我刚才看的demo。
首先是服务器端。。。
第一步 写一个aidl
IServer.aidl 定义接口,adt会自动在gen下面生成对应的java文件,该文件无需修改
package cx.aidl;
interface IServer{
String getValueFromServer();
}
第二部 实现接口
代码
package cx.aidl;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import cx.aidl.IServer.Stub;
public class ServerService extends Service{
public class ServerImple extends IServer.Stub{
public String getValueFromServer() throws RemoteException {
// TODO Auto-generated method stub
return "this is get from the server";
}
public IBinder asBinder() {
// TODO Auto-generated method stub
return null;
}
}
public IBinder onBind(Intent intent){
return new ServerImple();
}
}
服务器端就基本上完成了,但是请记住manifest里面注册service
<service android:name="cx.aidl.ServerService">
<intent-filter>
<action android:name="cx.aidl.ServerService" />
</intent-filter>
</service>
------------------------------------------------------------------------------------------
接下来就是在客户端调用服务器端了。
新建一个项目
首先,将服务器端的aidl文件(IServer.aidl)拷贝到客户端,注意:包名和文件名必须一致
然后就是调用服务器端了,使用了ServerConnection进行连接。代码如下:
代码
package cx.aildClient;
import cx.aidl.IServer;
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.util.Log;
import android.widget.Toast;
public class AidlClient extends Activity {
/** Called when the activity is first created. */
private IServer iServer = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.bindService(new Intent("cx.aidl.ServerService"), serverConnection, Context.BIND_AUTO_CREATE);
Log.d("cx","in onCreate()");
}
private ServiceConnection serverConnection = new ServiceConnection(){
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
iServer = IServer.Stub.asInterface(service);
try {
Toast.makeText(AidlClient.this, iServer.getValueFromServer(), Toast.LENGTH_LONG).show();
} catch (RemoteException e) {
// TODO Auto-generated catch block
Toast.makeText(AidlClient.this, "error!!!!!" , Toast.LENGTH_LONG).show();
}
}
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
}