1、在Eclipse中新建工程,名称为Client;然后把Server工程中的com.example.aidl包整个拷贝到Client工程的src目录下;工程结构如下所示
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/binderButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bind" />
<Button
android:id="@+id/unbinderButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="unbind" />
</LinearLayout>
package com.example.client;
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.widget.Button;
import com.example.aidl.IRemoteService;
public class MainActivity extends Activity {
private String TAG = "com.example.aidl";
private IRemoteService remoteService;
private Button mBindButton;
private Button mUnbindButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBindButton = (Button)findViewById(R.id.binderButton);
mBindButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d(TAG, "Bind Service");
//Intent intent = new Intent(IRemoteService.class.getName());
/*新建Intent,指定Service的AndroidMainfest.xml中声明的Action名称*/
Intent intent = new Intent("com.example.aidl");
/*在Android5.0以后,不允许隐式调用服务,故再次指定服务所在包名*/
intent.setPackage("com.example.service");
/*绑定服务*/
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
});
mUnbindButton = (Button)findViewById(R.id.unbinderButton);
mUnbindButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d(TAG, "UnBind Service");
/*解绑服务*/
unbindService(conn);
}
});
}
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "UnBind Service success!");
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "Bind Service success!");
/*获取服务端handle*/
remoteService = IRemoteService.Stub.asInterface(service);
try {
int pid1 = remoteService.getPid();
int pid2 = remoteService.basicTypes(12, 1223, true, 12.2f, 12.3, "我们的爱,我明白");
/*打印带有getPid接口和basicTypes接口时服务端的线程号*/
Log.d(TAG, &qu