(一) Extending the Binder class
通过 Binder 接口的形式实现,当 Activity 绑定 Service 成功的时候 Activity 会在<code> ServiceConnection </code>类的 <code>onServiceConnected()</code>回调方法中获取到 Service 的 onBind()方法 return 过来的 Binder 的子类。
(二)Using a Messenger
MessengerService.java
public class MessengerService extends Service {
private Messenger messenger = new Messenger(new IncomingHandler());
private Messenger mActivityMessenger;
@Override
public IBinder onBind(Intent intent) {
IBinder binder = messenger.getBinder();
return binder;
}
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
Log.d("tag", msg.toString());
if (mActivityMessenger != null) {
Message message = new Message();
message.what = 2;
message.obj = "地瓜地瓜我是土豆";
try {
mActivityMessenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
break;
case 1:
mActivityMessenger = (Messenger) msg.obj;
Log.d("tag", "已经获取到 Activity 发送了的 Messenger 对象");
break;
default:
break;
}
}
}
}
MessageActivity.java
public class MessageActivity extends AppCompatActivity {
private Messenger messenger;
private Messenger mOutMessenger = new Messenger(new OutgoingHandler());
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(MessageActivity.this, "连接成功!", Toast.LENGTH_SHORT).show();
messenger = new Messenger(service);
Message message = new Message();
message.what = 1;
message.obj = mOutMessenger;
try {
messenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(MessageActivity.this, "连接已经断开!", Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
}
/**
* 绑定服务
*
* @param view
*/
public void click1(View view) {
Intent intent = new Intent(this, MessengerService.class);
bindService(intent, conn, BIND_AUTO_CREATE);
}
/**
* 发送消息
*
* @param view
*/
public void click2(View view) {
if (messenger == null) {
Toast.makeText(this, "服务不可用!", Toast.LENGTH_SHORT).show();
return;
}
Message message = new Message();
message.obj = "长江长江我是黄河";
message.what = 0;
try {
messenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
class OutgoingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Log.d("tag", msg.toString());
}
}
}
(三)Using AIDL
AIDL 比较适合当客户端和服务端不在同一个应用下的场景。
有点多啊哈哈哈,可以看这篇IPC机制——AIDL的简单梳理