您的位置:首页 > 移动开发 > Android开发

android使用aidl实现进程间通信的实例

2013-07-22 18:20 549 查看
在开发Android应用时,由于不存在共享内在之类的机制,
android应用采用AIDL(Android Interface Definition Language:接口定义语言)方式实现进程间通信,下面我将写一个实例。

在eclipes中创建一个android工程,这里我的工程名为:com.wyj.aidltest,工程会创建一个com.wyj.aidltestActivity.java的文件

1,创建aidl文件及列举实现接口,右击aidltestActivity.java--〉New--〉File
填写aidl文件名,这里为IAidlTest.aidl,定义接口内容如下:

package
com.wyj;

interface IAidlTest{

void print(String str);

}

我这里就是想打印一个字符串。这一步做完后,eclipes会自动在gen中的com.wyj下生成一个IAidlTest.java文件;

2, 同样新建一个文件service.java实现服务端
public class service extends Service

{

final String TAG="SERVICE";

@Override

public IBinder onBind(Intent arg0) {

// TODO Auto-generated method stub

Log.i(TAG, "onBind()");

ServiceBinder svr= new ServiceBinder();

return svr;

}

public void onCreate(Bundle savedInstanceState) {

super.onCreate();

Log.i(TAG, "onCreate()");

}

public void onDestroy() {

super.onDestroy();

Log.i(TAG, "onDestroyed()");

}

public class ServiceBinder extends IAidlTest.Stub

{

public void print(String str)

{

Log.i(TAG, "str="+str);

}

}

}

3,在manifest.xml中增加这个服务,如果不增加在启动服务的时候,会找不到。
<service android:name="com.wyj.service">

<intent-filter >

<action android:name="com.wyj.aidlservice"/> ----〉这个是用作启动此服务的Intent参数

</intent-filter>

</service>>

4,在aidltestActivity.java中添加相关内容:
public class aidltestActivity extends Activity implements OnClickListener{

/** Called when the activity is first created. */

final String TAG="aidltestActivity";

private IAidlTest aidltest = null;

Button btn=null;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Log.i(TAG, "onCreate");

//这一步启动服务

this.bindService(new Intent("com.wyj.aidlservice"), this.serviceConnection, BIND_AUTO_CREATE);

btn = (Button)findViewById(R.id.button1);

btn.setOnClickListener(this);

}

private ServiceConnection serviceConnection = new ServiceConnection() {

public void onServiceConnected(ComponentName className, IBinder service) {

Log.i(TAG, "onServiceConnected");

aidltest = IAidlTest.Stub.asInterface(service);

}

//这个接口要实现,不然后报错

public void onServiceDisconnected(ComponentName className) {

Log.i(TAG, "onServiceDisconnected");

aidltest = null;

}

};

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

try {

Log.i(TAG, "onClick hello");

aidltest.print("hello");

} catch (RemoteException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public void onDestroy()

{

//记得要释放资源,要不会产生内在泄漏

this.unbindService(serviceConnection);

aidltest = null;

serviceConnection = null;

Log.i(TAG, "onDestroy");

super.onDestroy();

}

}

编写完后,在机器上运行,点击按钮,会在logcat中看到打印信息
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: