标签:
startService有个致命的弱点,startService无法将service运算的结果返回给activity,bindService正是解决这一问题
作为一个bindService他是充当服务器端的,其他的组件是充当客户端的,在activity中可以得到service运行的一些基本的情况
public class MainActivity extends Activity {
private Button button1;
private Button button2;
private Binder binder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondService.class);
bindService(intent, conn, BIND_AUTO_CREATE);
}
});
//transact和onTransact activity向service发送消息,service向activity返回消息
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeString("data from activity");
try {
binder.transact(0, data, reply, 0);
String string = reply.readString();
System.out.println("activity ---"+string);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (FirstBinder)service;
String data = ((FirstBinder) binder).getData();
System.out.println("data -->daya"+data);
}
};
}
public class SecondService extends Service {
//当其他的应用程序组件(activity)绑定至当前的service时,将会调用该方法
@Override
public IBinder onBind(Intent intent) {
IBinder binder = new FirstBinder();
return binder;
}
class FirstBinder extends Binder {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
System.out.println("code - >"+code);
String dataString = data.readString();
System.out.println("datastring = "+dataString);
reply.writeString("reply from service");
return super.onTransact(code, data, reply, flags);
}
public String getData() {
return "test data";
}
}
}
标签:
原文地址:http://www.cnblogs.com/zhangkefan/p/4847619.html