MainActivity
public class MainActivity
extends AppCompatActivity
{
private static final String TAG = "MainActivity";
private IBookManager.Stub mBookManager;
private IBinder.DeathRecipient mDeathRecipient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button secondBtn = findViewById(R.id.second);
Button third = findViewById(R.id.third);
secondBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SecondActivity.acrtionStart(MainActivity.this);
}
});
third.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ThirdActivity.acrtionStart(MainActivity.this);
}
});
}
@Override
protected void onResume() {
super.onResume();
new Thread(new Runnable() {
@Override
public void run() {
User user = new User(1, "Hello world", false);
File file = new File(getExternalCacheDir().getPath(),"test.text");
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
objectOutputStream.writeObject(user);
Log.d(TAG, "PERSIST USER:" + user);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objectOutputStream!=null)
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
SecondActivity
public class SecondActivity
extends AppCompatActivity
{
private static final String TAG = "MainActivity";
public static void acrtionStart(Context context){
context.startActivity(new Intent(context,SecondActivity.class));
}
private User mUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
recoverFromFile();
}
private void recoverFromFile() {
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(getExternalCacheDir().getPath(),"test.text");
ObjectInputStream objectInputStream=null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream(
file));
mUser = (User) objectInputStream.readObject();
Log.d(TAG,"recover user:"+mUser);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (objectInputStream!=null)
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
Log 日志
/**
* Create a new Messenger pointing to the given Handler. Any Message
* objects sent through this Messenger will appear in the Handler as if
* {@link Handler#sendMessage(Message) Handler.sendMessage(Message)} had
* been called directly.
*
* @param target The Handler that will receive sent messages.
*/
//关联的 Handler 会接收到发送的消息
public Messenger(Handler target) {
mTarget = target.getIMessenger();
}
/**
* Create a Messenger from a raw IBinder, which had previously been
* retrieved with {@link #getBinder}.
*
* @param target The IBinder this Messenger should communicate with.
*/
public Messenger(IBinder target) {
mTarget = IMessenger.Stub.asInterface(target);
}
public class MainActivity
extends AppCompatActivity
{
private static final String TAG = "MainActivity";
private Messenger mService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//创建 Messenger 对象
mService = new Messenger(service);
//创建消息载体 Message 对象
Message msg = Message.obtain(null, MyConstants.MSG_FROM_CLIENT);
//跨进程通信数据载体
Bundle data = new Bundle();
data.putString("msg","hello, this is client.");
//msg 装载 Bundle 数据
msg.setData(data);
try {
//Messenger 发送消息
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button secondBtn = findViewById(R.id.second);
Button third = findViewById(R.id.third);
secondBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MessengerService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
});
}
@Override
protected void onDestroy() {
unbindService(mConnection);
super.onDestroy();
}
}
public class MessengerService
extends Service
{
private static final String TAG = "MessengerService";
//构建 MessengerHandler 处理客户端发送的消息,并从消息中去除客户端发送来的文本信息
private static class MessengerHandler
extends Handler
{
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyConstants.MSG_FROM_CLIENT:
Log.i(TAG,
"receive msg from Client:" + msg.getData()
.get("msg"));
break;
default:
super.handleMessage(msg);
break;
}
}
}
//通过 MessengerHandler 构建 Messenger 对象,关联 MessengerHandler
private final Messenger mMessenger = new Messenger(new MessengerHandler());
@Override
public IBinder onBind(Intent intent) {
//返回 Messenger 的 Binder 对象
return mMessenger.getBinder();
}
}
public class MainActivity
extends AppCompatActivity
{
private static final String TAG = "MainActivity";
private Messenger mService;
private static class MessengerHander extends Handler{
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyConstants.MSG_FROM_SERVICE://接收服务端发送的消息
Log.i(TAG,
"receive msg from Client:" + msg.getData()
.get("reply"));
break;
default:
super.handleMessage(msg);
break;
}
}
}
private Messenger mGetReplyMessenger = new Messenger(new MessengerHander());
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
/**
* Create a Messenger from a raw IBinder, which had previously been
* retrieved with {@link #getBinder}.
*
* @param target The IBinder this Messenger should communicate with.
*/
//从服务端获取 Binder 对象,然后创建 Messenger 对象,属于服务端?
mService = new Messenger(service);
//创建消息载体 Message 对象
Message msg = Message.obtain(null, MyConstants.MSG_FROM_CLIENT);
//跨进程通信数据载体
Bundle data = new Bundle();
data.putString("msg","hello, this is client.");
//msg 装载 Bundle 数据
msg.setData(data);
//将这个信使存储在msg的replyTo中,给服务端发消息用
msg.replyTo = mGetReplyMessenger;
try {
//Messenger 发送消息
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button secondBtn = findViewById(R.id.second);
Button third = findViewById(R.id.third);
secondBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MessengerService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
});
third.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ThirdActivity.acrtionStart(MainActivity.this);
}
});
}
@Override
protected void onDestroy() {
unbindService(mConnection);
super.onDestroy();
}
}
public class MessengerService
extends Service
{
private static final String TAG = "MessengerService";
//构建 MessengerHandler 处理客户端发送的消息,并从消息中去除客户端发送来的文本信息
private static class MessengerHandler
extends Handler
{
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyConstants.MSG_FROM_CLIENT:
Log.i(TAG,
"receive msg from Client:" + msg.getData()
.get("msg"));
//获取 msg.replyTo 中的 Messenger,即客户端发送过来的Messenger
Messenger client = msg.replyTo;
Message relpyMessage = Message.obtain(null, MyConstants.MSG_FROM_SERVICE);
Bundle bundle = new Bundle();
bundle.putString("reply","嗯,你的消息我已经收到,稍后会回复你。");
relpyMessage.setData(bundle);
try {
client.send(relpyMessage);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
break;
}
}
}
//通过 MessengerHandler 构建 Messenger 对象,关联 MessengerHandler
private final Messenger mMessenger = new Messenger(new MessengerHandler());
@Override
public IBinder onBind(Intent intent) {
/**
* Retrieve the IBinder that this Messenger is using to communicate with
* its associated Handler.
*
* @return Returns the IBinder backing this Messenger.
*/
//返回 Messenger 的 Binder 对象
return mMessenger.getBinder();
}
}
log 日志:
03-07 10:34:19.875 25823-25823/? I/MessengerService: receive msg from Client:hello, this is client.
03-07 10:34:19.875 25723-25723/com.example.yhadmin.aidldemo I/MainActivity: receive msg from Client:嗯,你的消息我已经收到,稍后会回复你。
private Messenger mGetReplyMessenger = new Messenger(new MessengerHander());
通过关联的Handler 获取 IMessenger 对象
private final IMessenger mTarget;
/**
* Create a new Messenger pointing to the given Handler. Any Message
* objects sent through this Messenger will appear in the Handler as if
* {@link Handler#sendMessage(Message) Handler.sendMessage(Message)} had
* been called directly.
*
* @param target The Handler that will receive sent messages.
*/
public Messenger(Handler target) {
mTarget = target.getIMessenger();
}
Handler 中的 getIMessenger 方法
final IMessenger getIMessenger() {
synchronized (mQueue) {
if (mMessenger != null) {
return mMessenger;
}
mMessenger = new MessengerImpl();
return mMessenger;//返回Messenger 对象,
}
}
private final class MessengerImpl extends IMessenger.Stub {
public void send(Message msg) {
msg.sendingUid = Binder.getCallingUid();//存储当前进程的 Uid
Handler.this.sendMessage(msg);//通过Handler 发送消息
}
}
Messenger发送消息
//Messenger 发送消息
mService.send(msg);
在源码中调用的是 MessengerImpl 的 send 方法,最终调用的是Handler 的 sendMessage(msg)方法
/**
* Send a Message to this Messenger's Handler.
*
* @param message The Message to send. Usually retrieved through
* {@link Message#obtain() Message.obtain()}.
*
* @throws RemoteException Throws DeadObjectException if the target
* Handler no longer exists.
*/
public void send(Message message) throws RemoteException {
mTarget.send(message);
}
通过 IBinder 对象构建 Messenger 对象
//从服务端获取 Binder 对象,然后创建 Messenger 对象,属于服务端?
mService = new Messenger(service);
源码:
/**
* Create a Messenger from a raw IBinder, which had previously been
* retrieved with {@link #getBinder}.
*
* @param target The IBinder this Messenger should communicate with.
*/
public Messenger(IBinder target) {
mTarget = IMessenger.Stub.asInterface(target);
}
而这个IBinder 对象是通过绑定服务端时,回传给客户端的
@Override
public IBinder onBind(Intent intent) {
/**
* Retrieve the IBinder that this Messenger is using to communicate with
* its associated Handler.
*
* @return Returns the IBinder backing this Messenger.
*/
//返回 Messenger 的 Binder 对象
return mMessenger.getBinder();
}
查看源码可知该IBinder 对象实质上就是通过 IMessenger获取的
/**
* Retrieve the IBinder that this Messenger is using to communicate with
* its associated Handler.
*
* @return Returns the IBinder backing this Messenger.
*/
public IBinder getBinder() {
return mTarget.asBinder();
}