第一步创建一个aidl文件如图:
以下是客户端:
package com.example.k.aidldemo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int c=0;
Button b,b1;
String str;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IBookList i = IBookList.Stub.asInterface(service);
try {
i.getString(11);
i.method();
str = i.getValue();
}catch(Exception e){
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button);
b1 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"服务器返回的值为:"+str,Toast.LENGTH_SHORT).show();
}
});
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MyService.class);
bindService(intent,connection, Context.BIND_AUTO_CREATE);
}
});
}
}
以下是服务端:
package com.example.k.aidldemo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by k on 2016/6/6.
*/
public class MyService extends Service {
int b = 0;
private Binder binder = new IBookList.Stub(){
public void getString(int a) throws RemoteException{
b = a;
}
public void method()throws RemoteException{
Log.i("ok","服务的b="+b);
}
public String getValue() throws RemoteException{
return "ok!ok!";
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
以下是aidl文件:
// IBookList.aidl
package com.example.k.aidldemo;
// Declare any non-default types here with import statements
interface IBookList {
void getString(in int a);
void method();
String getValue();
}
以上实现了,不同进程间的互相通信。