相对比,使用Transact比使用Messenger简单的多。了解BinderService基础,这个就so easy
MyService.java
-
package com.vibexie.servicetransact;
-
-
import android.app.Service;
-
import android.content.Intent;
-
import android.os.Binder;
-
import android.os.IBinder;
-
import android.os.Parcel;
-
import android.os.RemoteException;
-
-
public class MyService extends Service {
-
@Override
-
public void onCreate() {
-
super.onCreate();
-
}
-
-
public MyService() {
-
}
-
-
public class MyBinder extends Binder{
-
@Override
-
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
-
reply.writeString(data.readString()+" and juan");
-
return super.onTransact(code, data, reply, flags);
-
}
-
}
-
@Override
-
public IBinder onBind(Intent intent) {
-
// TODO: Return the communication channel to the service.
-
return new MyBinder();
-
}
- }
MainActivity.java
-
package com.vibexie.servicetransact;
-
-
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.RemoteException;
-
import android.support.v7.app.ActionBarActivity;
-
import android.os.Bundle;
-
import android.view.View;
-
import android.widget.Button;
-
import android.widget.Toast;
-
-
-
public class MainActivity extends ActionBarActivity {
-
/**
-
* 与service建立连接的Binder
-
*/
-
MyService.MyBinder myBinder;
-
private Button button;
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main);
-
button=(Button)this.findViewById(R.id.button);
-
Intent intent=new Intent(this,MyService.class);
-
bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);
-
-
button.setOnClickListener(new View.OnClickListener() {
-
@Override
-
public void onClick(View v) {
-
/**
-
* 向service发送的Parcel
-
*/
-
Parcel parcel=Parcel.obtain();
-
parcel.writeString("vibexie");
-
/**
-
* 用于接收service返回数据的parcel
-
*/
-
Parcel reply=Parcel.obtain();
-
-
/**
-
* 与Service进行交互
-
*/
-
try {
-
myBinder.transact(IBinder.FIRST_CALL_TRANSACTION, parcel, reply, 0);
-
} catch (RemoteException e) {
-
e.printStackTrace();
-
}
-
-
/**
-
* 获取返回数据
-
*/
-
Toast.makeText(MainActivity.this,reply.readString(),Toast.LENGTH_SHORT).show();
-
}
-
});
-
}
-
-
ServiceConnection serviceConnection=new ServiceConnection() {
-
@Override
-
public void onServiceConnected(ComponentName name, IBinder service) {
-
myBinder = (MyService.MyBinder)service;
-
}
-
-
@Override
-
public void onServiceDisconnected(ComponentName name) {
-
-
}
-
};
- }