Android Messenger原理

前言

Messenger中文意思是送信者,經過Messenger咱們能夠在不一樣進程之間傳遞Message對象,其底層也是經過上文講到的AIDL實現的,先來看看基本用法java

1、基本用法

以客戶端發送消息給服務端,服務端回覆一個消息給客戶端爲例。ide

// 運行在其它進程
class MessengerService : Service() {
    class MessengerHandler : Handler() {
        val TAG = "MessengerHandler"
        override fun handleMessage(msg: Message?) {
            when (msg?.what) {
                ADD_BOOK -> {
                    // 必須設置classLoader否則會拋出異常
                    msg.data.classLoader = Thread.currentThread().contextClassLoader
                    Log.d(TAG, "do add book ${msg.data.get("book")}")
                    val replyMessage = Message.obtain(null, REPLY_ADD_BOOK)
                    val bundle = Bundle()
                    bundle.putString("reply", "我收到了響應")
                    replyMessage.data = bundle
                    msg.replyTo.send(replyMessage)
                }
                ALL_BOOKS -> {
                    Log.d(TAG, "do all books")
                }
            }
        }
    }
    override fun onBind(intent: Intent?): IBinder? {
        val messenger = Messenger(MessengerHandler())
        return messenger.binder
    }
}
複製代碼

接着在MainActivity中綁定服務,代碼以下源碼分析

class MainActivity : AppCompatActivity() {

    private lateinit var connection: ServiceConnection
    private lateinit var replyMessenger: Messenger
    private var messenger: Messenger? = null
    
    class GetReplyHandler : Handler() {
        private var TAG = "MainActivity"
        override fun handleMessage(msg: Message?) {
            when (msg?.what) {
                REPLY_ADD_BOOK -> {
                    Log.d(TAG, msg.data.getString("reply"))
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        connection = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                messenger = Messenger(service)
            }
            override fun onServiceDisconnected(name: ComponentName?) {
            }
        }
        replyMessenger = Messenger(GetReplyHandler())
        val intent = Intent(this, MessengerService::class.java)
        bindService(intent, connection, Context.BIND_AUTO_CREATE)
    }

    fun send(v: View) {
        val msg = Message.obtain(null, ADD_BOOK)
    // msg.obj = Book(0, "第0本書") 不能使用obj跨進程傳遞自定義的Parcelable對象,使用Bundle由於其能夠設置classLoader
        val msg = Message.obtain(null, ADD_BOOK)
        val bundle = Bundle()
        bundle.putParcelable("book", Book(0, "第0本書"))
        msg.data = bundle
        msg.replyTo = replyMessenger
        messenger?.send(msg)
    }
    
    override fun destroy() {
        unbindService(connection)
    }
}
複製代碼

注意send方法內部發送的Parcelable類(這裏是Book)在服務端必須也要存在,這樣當調用MainActivity的send方法時就會服務進程就會打印出do add book,下面就來看看該過程的源碼post

2、源碼分析

  • 客戶端發送消息給服務端

首先咱們在MessengerService的onBind中建立了一個Messenger實例,因此咱們就從Messenger構造器開始提及this

public Messenger(Handler target) {
    mTarget = target.getIMessenger();
}
複製代碼

繼續看看Handler的getIMessagerspa

final IMessenger getIMessenger() {
    synchronized (mQueue) {
        if (mMessenger != null) {
            return mMessenger;
        }
        mMessenger = new MessengerImpl();
        return mMessenger;
    }
}
複製代碼

剛開始mMessenger確定爲null,繼續看看MessengerImpl線程

private final class MessengerImpl extends IMessenger.Stub {
    public void send(Message msg) {
        msg.sendingUid = Binder.getCallingUid();
        Handler.this.sendMessage(msg);
    }
}
複製代碼

這裏竟然有個Stub!瞬間想起了AIDL,因而就去找了找有沒有IMessenger.aidl這個文件,最終找到了該文件,文件內容以下code

oneway interface IMessenger {
    void send(in Message msg);
}
複製代碼

這裏的oneway表示調用send方法並不會掛起當前線程等待服務端執行,而是會當即返回,send方法實現爲將收到的消息發送給建立Messenger時的入參,至此服務端的Messenger使用分析完畢接着看看客戶端中Messenger的使用,在onServiceConnected中經過傳入的Binder對象構造了Messenger對象。對象

public Messenger(IBinder target) {
    mTarget = IMessenger.Stub.asInterface(target);
}
複製代碼

調用asInterface(上篇文章有講到)拿到IMessenger.Stub.Proxy實例賦值給mTarget,最後客戶端經過調用Messengr.send發送消息進程

public void send(Message message) throws RemoteException {
    mTarget.send(message);
}
複製代碼

無論這裏send是個直接調用仍是IPC調用都會調用到如下MessengerImpl的send方法,該方法又把消息發送到了對應的Handler,所以服務端的Handler就能收到消息了

  • 服務端收到消息回覆客戶端

注意客戶端將replyMessenger設置給了Message.replyTo而後發送消息,這個過程當中會調用Message.writeToParcel

public void writeToParcel(Parcel dest, int flags) {
    if (callback != null) {
        throw new RuntimeException(
            "Can't marshal callbacks across processes.");
    }
    dest.writeInt(what);
    dest.writeInt(arg1);
    dest.writeInt(arg2);
    if (obj != null) {
        try {
            Parcelable p = (Parcelable)obj;
            dest.writeInt(1);
            dest.writeParcelable(p, flags);
        } catch (ClassCastException e) {
            throw new RuntimeException(
                "Can't marshal non-Parcelable objects across processes.");
        }
    } else {
        dest.writeInt(0);
    }
    dest.writeLong(when);
    dest.writeBundle(data);
    Messenger.writeMessengerOrNullToParcel(replyTo, dest);
    dest.writeInt(sendingUid);
}
複製代碼

又會調用到Messenger.writeMessengerOrNullToParcel

public static void writeMessengerOrNullToParcel(Messenger messenger, Parcel out) {
    out.writeStrongBinder(messenger != null ? messenger.mTarget.asBinder()
            : null);
}
複製代碼

向Parcel中寫入了一個MessengerImpl實例(Binder),而後在IPC結束後會調用Message.readFromParcel

private void readFromParcel(Parcel source) {
    what = source.readInt();
    arg1 = source.readInt();
    arg2 = source.readInt();
    if (source.readInt() != 0) {
        obj = source.readParcelable(getClass().getClassLoader());
    }
    when = source.readLong();
    data = source.readBundle();
    replyTo = Messenger.readMessengerOrNullFromParcel(source);
    sendingUid = source.readInt();
}
複製代碼

又調用到了Messenger.readMessengerOrNullFromParcel

public static Messenger readMessengerOrNullFromParcel(Parcel in) {
    IBinder b = in.readStrongBinder();
    return b != null ? new Messenger(b) : null;
}
複製代碼

若是是跨進程傳遞那麼讀取的會是一個BinderProxy對象,經過該BinderProxy構造Messenger對象其內部的mTarget就會是一個IMessenger.Stub.Proxy實例,所以服務端就能夠調用客戶端的對應方法了

相關文章
相關標籤/搜索