利用介面實現service與Activity訊息傳遞
阿新 • • 發佈:2019-01-27
背景
最近在仿Android版QQ,在實現訊息傳遞的時候遇到一個問題:當service接收到一條聊天訊息後,需要將該聊天訊息傳遞給聊天介面,但怎麼能是訊息無延時的在service和Activity中傳遞呢?
一般的做法是使用廣播,如在音樂播放器中播放進度的顯示等,而使用廣播發送訊息時,會因為Android系統的影響而導致訊息不能按時傳送過去,因此研究了下使用介面無延時的傳遞。
原理
1、定義一個介面 如:ReceiveMsgInterface
2、在service中定義一個上述介面的物件,如receiveMsgInterface
3、在自定義IBinder類中定義一個賦值該receiveMsgInterface的方法,如onRecMessage(QQMessage msg);
4、當service接收到一個聊天訊息後,呼叫receiveMsgInterface.onRecMessage(msg);
5、讓聊天Activity實現receiveMsgInterface介面
6、當Activity通過bindService成功繫結該service後,呼叫2中IBinder中的賦值方法。
事例程式碼
Activity:
Intent service = new Intent(this, ReceiveMessageService.class);
conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e("onServiceDisconnected", name.toShortString());
}
//newsFragment是Activity中的一個fragment,且newsFragment實現RceiveMsgInterface介面
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
((MyBinder) service).addReceiverMessageInterface(newsFragment);
}
};
bindService(service, conn, BIND_AUTO_CREATE);
service:
public void receiverMessage (QQMessage msg) {
if (msg.type.equals(QQMessageType.MSG_TYPE_CHAT_P2P)) {
if (receiverMessageInterface!=null) {
receiverMessageInterface.onGetOneMessage(msg);
}
}
}
private receiveMsgInterface receiverMessageInterface;
public class MyBinder extends Binder {
public void addReceiverMessageInterface(receiveMsgInterfacermInterface){
receiverMessageInterface = rmInterface;
}
}
NewsFragment:
public class NewsFragment extends BaseFragment implements receiveMsgInterface{
xxxx;
@Override
public void onGetOneMessage(QQMessage msg) {
Message message = Message.obtain();
message.what =2;
message.obj=msg;
handler.sendMessage(message);
}
}