服务:
package com.example.test3;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;
public class MyService extends Service {
private static final java.lang.String DESCRIPTOR = "com.example.test3.aa";
static final int TRANSACTION_ss = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
private static final String TAG = "MyService3";
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind");
return new MyBinder();
}
class MyBinder extends Binder {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_ss: {
data.enforceInterface(DESCRIPTOR);
reply.writeNoException();
int i = data.readInt();
Log.e(TAG, "MyService3 " + i);
reply.writeInt(i);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
}
}
客户端:
package com.example.test4;
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;
public class Client extends Activity implements OnClickListener {
private static final String TAG = "MainActivity";
aa mProxy ;
private static final java.lang.String DESCRIPTOR = "com.example.test3.aa";
static final int TRANSACTION_ss = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
this.findViewById(R.id.button1).setOnClickListener(this);
Intent service = new Intent("com.example.test3.MyService2");
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder obj) {
mProxy =new Proxy(obj);
}
};
this.bindService(service, conn, Context.BIND_AUTO_CREATE);
}
private static class Proxy implements aa {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
public int ss(int i) {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result=-1;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(i);
mRemote.transact(TRANSACTION_ss, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
} catch (RemoteException e) {
e.printStackTrace();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
@Override
public void onClick(View v) {
Log.e(TAG, "" + mProxy.ss(752));
}
}
重要: Binder.onTransact IBinder.transact