4.客户端代码:(绑定远程Service,然后获取Binder对象,然后进行数据交换和方法调用)
package com.wenix.Androidclient;
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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.wenix.service.aidl.IPerson;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private class PersonServiceConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName cmp, IBinder service) {
//客户端在这个回调方法中获得Binder对象
IPerson p = IPerson.Stub.asInterface(service);
try {
//这里调用AIDL规定的接口来获取数据
Log.i(TAG, p.getPerson(1).toString());
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//界面采用动态布局
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setLayoutParams(params);
btn.setText("获取Service数据");
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//启动相应的Service,由于是远程Service,所以不能使用显示Intent
Intent service = new Intent("com.wenix.intent.action.AIDL_SERVICE");
PersonServiceConnection conn = new PersonServiceConnection();
bindService(service, conn, Context.BIND_AUTO_CREATE);
}
});
TextView tv = new TextView(this);
tv.setLayoutParams(params);
ll.addView(btn);
ll.addView(tv);
setContentView(ll);
}
}
工程彻底完成,然后我们运行后点击Button,就可以看到获取的数据:
只需掌握整个流程,AIDL就可以很容易的使用。后期会加入一些使用AIDL的具体实例。