android AIDL双向通信简单实现

android AIDL双向通信简单实现

首先设置监听,定义AIDL 接口:
IListener.aidl 文件:
package com.example.servicesss;
interface IListener{
void sendMsgtoClient(String msg); (service消息给client)
}
再设置回调。
ICallback.aidl 文件:
package com.example.servicesss;
import com.example.servicesss.IListener;
interface ICallback{
void setListener(IListener lst);(设置监听)//重点关键代码在这里
void sendMSGtoService(String msg); (client发消息到 service)
}

写service.java文件:

public class MyService extends Service {

private static final String TAG = "aidltest";

@Override
public void onCreate() {

	new Thread(new Runnable() {

		@Override
		public void run() {
			int i = 0;
			while (true) {
				i++;
				if (listener != null) {
					try {
						listener.sendMsgtoClient(i + "");
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}).start();

}

@Override
public IBinder onBind(Intent t) {

	return iCallback;
}

private IListener listener;
private ICallback.Stub iCallback = new ICallback.Stub() {

	@Override
	public void setListener(IListener lst) throws RemoteException {
		listener = lst;
	}

	@Override
	public void sendMSGtoService(String msg) throws RemoteException {
		Log.i(TAG + "service", msg);
	}

};

}

MainActivity客户端:
public class MainActivity extends Activity {
bindService(intent, mConnection, BIND_AUTO_CREATE);
//已删除部分无关代码
ICallback callbcak;
private ServiceConnection mConnection = new ServiceConnection() {

	public void onServiceConnected(ComponentName className, IBinder service) {
		callbcak = ICallback.Stub.asInterface(service);
		
		new Thread( new Runnable() {
			int   i=500;
			@Override
			public void run() {
				while(true){
					i++;
					try {
						callbcak.sendMSGtoService(i + "service");   (发消息到service)
					} catch (RemoteException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
		}).start();
		
		
		
		try {
			callbcak.setListener(new IListener.Stub() {// 设置监听

				@Override
				public void sendMsgtoClient(String msg)
						throws RemoteException {  
					Log.i("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD", msg);//接收服务器发过来的信息
					
				}

				
			});
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		
	}

	public void onServiceDisconnected(ComponentName className) {

	}
};

}