Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android AIDL的一些寫法

android AIDL的一些寫法

編輯:關於Android編程

Service這邊只要定義一個服務:

 
            
                
            
            
        

對於傳遞的是基本類型:創建要傳遞的數據類型:

interface IDog{
	String getName();
	int getAge();	
}

然後在服務器的Service上創建Stub,Stub是存根的意思,在客戶端也有一個一樣的IDog類,通信的時候傳遞的都是IDog類型:

服務端Service的寫法:

import com.example.aidlservicedemo.domain.IDog.Stub;

public class BaseTypeService extends Service {
	private final String TAG="main";
	private DogBinder binder=null;
	private String[] names=new String[]{"小白","旺財","小黑"};
	private int[] ages=new int[]{1,2,3};
	
	/**
	 * Stub的實現類,Stub內部實現了Binder
	 * 內部實現AIDL定義的方法
	 */
	public class DogBinder extends Stub{

		@Override
		public String getName() throws RemoteException {
			return names[0];
		}

		@Override
		public int getAge() throws RemoteException {
			return ages[1];
		}		
	}
	
	
	@Override
	public void onCreate() {
		super.onCreate();
		// 實例化Binder對象
		binder=new DogBinder();
		Log.i(TAG, "創建服務成功");
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.i(TAG, "綁定服務成功");
		// 返回Binder對象
		return binder;
	}
}

客戶端這樣來調用:

public class BaseTypeActivity extends Activity {
	private Button btn_startService, btn_endService,btn_getServiceData;
	private IDog dogService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_service);

		btn_startService = (Button) findViewById(R.id.btn_startService);
		btn_endService = (Button) findViewById(R.id.btn_endService);
		btn_getServiceData = (Button) findViewById(R.id.btn_getServiceData);

		btn_startService.setOnClickListener(click);
		btn_endService.setOnClickListener(click);
		btn_getServiceData.setOnClickListener(click);
	}

	private View.OnClickListener click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_startService:
				startService();
				break;
			case R.id.btn_endService:
				endService();
				break;
			case R.id.btn_getServiceData:
				getServiceDate();
				break;
			}
		}				
	};
	/*
	 * 獲取數據
	 */
	private void getServiceDate() {
		try {
			if(dogService!=null){
				StringBuilder sBuilder=new StringBuilder();
				sBuilder.append("name:"+dogService.getName());
				sBuilder.append("\nage:"+dogService.getAge());//獲取數據,這個結果應該是小白,2
				Toast.makeText(BaseTypeActivity.this, sBuilder.toString(), Toast.LENGTH_SHORT).show();
			}
			else
			{
				Toast.makeText(BaseTypeActivity.this, "請先綁定服務", Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}

	private ServiceConnection connBase=new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			dogService=null;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// IDog.Stub.asInterface,獲取接口
			dogService=IDog.Stub.asInterface(service);//表示拿到的這個Service對象
		}
	};
	
	/**
	 * 開始服務
	 */
	private void startService(){
		Intent intent=new Intent();
		intent.setAction("cn.bgxt.Service.BASE_TYPE_SERVICE");//這個必須跟服務端menufest上的action一致
		bindService(intent, connBase, BIND_AUTO_CREATE);
		Toast.makeText(BaseTypeActivity.this, "開始綁定服務", Toast.LENGTH_SHORT).show();
	}
	/**
	 * 停止服務
	 */
	private void endService(){
		if(connBase!=null)
		{
			unbindService(connBase);
			Toast.makeText(BaseTypeActivity.this, "服務解除綁定", Toast.LENGTH_SHORT).show();
		}
	}	
}


如果AIDL通訊傳遞是自定義類型:

一個常用的根據user來返回對象message信息的例子,user ,message都是自定義類型:

public class Message implements Parcelable {

	private int id;
	private String msgText;
	private String fromName;
	private String date;
}
public class User implements Parcelable {
	
	
	private int id;
	private String username;
	private String password;
}

定義兩個AIDL文件

message.aidl:

parcelable Message;

user.aidl

parcelable User;

服務器代碼:

public class CustomTypeService extends Service {
	private static final String TAG = "main";
	private MsgBinder msgBinder = null;
	private static Map> map = new HashMap>();
	static {
		for (int i = 0; i < 3; i++) {
			User user = new User(i, "jack" + i, "99" + i);
			List messages = new ArrayList();
			Message msg = null;
			if (i == 0) {
				msg = new Message(i, "這兩天好嗎?", "Jerry",
						new Date().toGMTString());
				messages.add(msg);
			}
			map.put(user, messages);
		}
	}

	public class MsgBinder extends Stub {

		@Override
		public List getMes(User us) throws RemoteException {
			for (Map.Entry> msgs : map.entrySet()) {
				if (msgs.getKey().getUsername().equals(us.getUsername())
						&& msgs.getKey().getPassword().equals(us.getPassword())) {
					Log.i(TAG, "找到信息了");
					return msgs.getValue();
				}
			}
			Log.i(TAG, "沒找到信息了");
			return map.get(us);
		}

	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return msgBinder;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		msgBinder = new MsgBinder();
	}

	@Override
	public void onDestroy() {
		msgBinder = null;
		super.onDestroy();
	}

}

客戶端基本是一致的:

private static User[] users = new User[] {
			new User(0, "jack0", "990")};
	
/**
	 * 獲取其他線程服務數據
	 */
	private void getServiceDate(){
		try {
			List msgs=getMsg.getMes(users[0]);
			StringBuilder sBuilder=new StringBuilder();
			for(Message msg:msgs){
				sBuilder.append(msg.toString()+"\n");
			}
			Toast.makeText(CustomTypeActivity.this, sBuilder.toString(), Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			Toast.makeText(CustomTypeActivity.this, "獲取數據出錯", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved