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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章