android AIDL实现详解

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;
	@Override
	public IBinder onBind(Intent arg0) {
		return new IMyService.Stub(){

			@Override
			public 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() {
			
			@Override
			public 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() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			myService = null;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			myService = IMyService.Stub.asInterface(service);
			
		}
	};
}


工程下载地址:

http://download.csdn.net/detail/jiang4920/4697723

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值