⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatsessionadapter.java

📁 Android平台上即时通讯聊天工具源代码。 支持手机聊天。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.android.im.service;import com.android.im.IChatListener;import com.android.im.IChatSession;import com.android.im.engine.ChatGroup;import com.android.im.engine.ChatGroupManager;import com.android.im.engine.ChatSession;import com.android.im.engine.Contact;import com.android.im.engine.GroupListener;import com.android.im.engine.GroupMemberListener;import com.android.im.engine.ImConnection;import com.android.im.engine.ImEntity;import com.android.im.engine.ImErrorInfo;import com.android.im.engine.Message;import com.android.im.engine.MessageListener;import com.android.im.engine.Presence;import android.content.ContentResolver;import android.content.ContentValues;import android.content.ContentUris;import android.database.Cursor;import android.net.Uri;import android.os.RemoteException;import android.provider.BaseColumns;import android.provider.Im;import android.util.Log;import java.util.ArrayList;import java.util.HashMap;import java.util.List;public class ChatSessionAdapter extends IChatSession.Stub {    private static final String NON_CHAT_MESSAGE_SELECTION = Im.BaseMessageColumns.TYPE            + "!=" + Im.MessageType.INCOMING + " AND " + Im.BaseMessageColumns.TYPE            + "!=" + Im.MessageType.OUTGOING;    static final String TAG = RemoteImService.TAG;    ImConnectionAdapter mConnection;    ChatSessionManagerAdapter mChatManager;    ChatSession mAdaptee;    ListenerAdapter mListenerAdapter;    boolean mIsGroupChat;    StatusBarNotifier mStatusBarNotifier;    private ContentResolver mContentResolver;    /*package*/Uri mChatURI;    private Uri mMessageURI;    private boolean mConvertingToGroupChat;    private static final int MAX_HISTORY_COPY_COUNT = 10;    private HashMap<String, Integer> mContactStatusMap = new HashMap<String, Integer>();    public ChatSessionAdapter(ChatSession adaptee,            ImConnectionAdapter connection) {        mAdaptee = adaptee;        mConnection = connection;        RemoteImService service = connection.getContext();        mContentResolver = service.getContentResolver();        mStatusBarNotifier = service.getStatusBarNotifier();        mChatManager = (ChatSessionManagerAdapter) connection.getChatSessionManager();        mListenerAdapter = new ListenerAdapter();        mAdaptee.addMessageListener(mListenerAdapter);        ImEntity participant = mAdaptee.getParticipant();        if(participant instanceof ChatGroup) {            init((ChatGroup)participant);        } else {            init((Contact)participant);        }    }    private void init(ChatGroup group) {        mIsGroupChat = true;        long groupId = insertGroupContactInDb(group);        group.addMemberListener(mListenerAdapter);        mMessageURI = ContentUris.withAppendedId(                Im.GroupMessages.CONTENT_URI_GROUP_MESSAGES_BY, groupId);        mChatURI = ContentUris.withAppendedId(Im.Chats.CONTENT_URI, groupId);        insertOrUpdateChat(null);        for (Contact c : group.getMembers()) {            mContactStatusMap.put(c.getName(), c.getPresence().getStatus());        }    }    private void init(Contact contact) {        mIsGroupChat = false;        ContactListManagerAdapter listManager =            (ContactListManagerAdapter) mConnection.getContactListManager();        long contactId = listManager.queryOrInsertContact(contact);        long provider = mConnection.getProviderId();        long account  = mConnection.getAccountId();        String address = contact.getAddress().getFullName();        mMessageURI = Im.Messages.getContentUriByContact(provider, account, address);        mChatURI = ContentUris.withAppendedId(Im.Chats.CONTENT_URI, contactId);        insertOrUpdateChat(null);        mContactStatusMap.put(contact.getName(), contact.getPresence().getStatus());    }    private ChatGroupManager getGroupManager() {        return mConnection.getAdaptee().getChatGroupManager();    }    public ChatSession getAdaptee() {        return mAdaptee;    }    public Uri getChatUri() {        return mChatURI;    }    public String[] getPariticipants() {        if (mIsGroupChat) {            Contact self = mConnection.getLoginUser();            ChatGroup group = (ChatGroup)mAdaptee.getParticipant();            List<Contact> members = group.getMembers();            String[] result = new String[members.size() - 1];            int index = 0;            for (Contact c : members) {                if (!c.equals(self)) {                    result[index++] = c.getAddress().getFullName();                }            }            return result;        } else {            return new String[] {mAdaptee.getParticipant().getAddress().getFullName()};        }    }    /**     * Convert this chat session to a group chat. If it's already a group chat,     * nothing will happen. The method works in async mode and the registered     * listener will be notified when it's converted to group chat successfully.     *     * Note that the method is not thread-safe since it's always called from     * the UI and Android uses single thread mode for UI.     */    public void convertToGroupChat() {        if (mIsGroupChat || mConvertingToGroupChat) {            return;        }        mConvertingToGroupChat = true;        new ChatConvertor().convertToGroupChat();    }    public boolean isGroupChatSession() {        return mIsGroupChat;    }    public String getName() {        return mAdaptee.getParticipant().getAddress().getScreenName();    }    public String getAddress() {        return mAdaptee.getParticipant().getAddress().getFullName();    }    public long getId() {        return ContentUris.parseId(mChatURI);    }    public void inviteContact(String contact) {        if(!mIsGroupChat){            return;        }        ContactListManagerAdapter listManager =            (ContactListManagerAdapter) mConnection.getContactListManager();        Contact invitee = listManager.getContactByAddress(contact);        if(invitee == null) {            ImErrorInfo error = new ImErrorInfo(ImErrorInfo.ILLEGAL_CONTACT_ADDRESS,                "Cannot find contact with address: " + contact);            mListenerAdapter.onError((ChatGroup)mAdaptee.getParticipant(), error);        } else {            getGroupManager().inviteUserAsync((ChatGroup)mAdaptee.getParticipant(),                    invitee);        }    }    public void leave() {        if (mIsGroupChat) {            getGroupManager().leaveChatGroupAsync((ChatGroup)mAdaptee.getParticipant());            mContentResolver.delete(mMessageURI, null, null);        } else {            mContentResolver.delete(mMessageURI, NON_CHAT_MESSAGE_SELECTION, null);        }        mContentResolver.delete(mChatURI, null, null);        mStatusBarNotifier.dismissChatNotification(                mConnection.getProviderId(), getAddress());        mChatManager.closeChatSession(this);    }    public void sendMessage(String text) {        if (mConnection.getState() == ImConnection.SUSPENDED) {            // connection has been suspended, save the message without send it            insertMessageInDb(null, text, -1, Im.MessageType.POSTPONED);            return;        }        Message msg = new Message(text);        mAdaptee.sendMessageAsync(msg);        long now = System.currentTimeMillis();        insertMessageInDb(null, text, now, Im.MessageType.OUTGOING);    }    void sendPostponedMessages() {        String[] projection = new String[] {            BaseColumns._ID,            Im.BaseMessageColumns.BODY,            Im.BaseMessageColumns.DATE,            Im.BaseMessageColumns.TYPE,        };        String selection = Im.BaseMessageColumns.TYPE + "=?";        Cursor c = mContentResolver.query(mMessageURI, projection, selection,                new String[]{Integer.toString(Im.MessageType.POSTPONED)}, null);        if (c == null) {            Log.e(TAG, "Query error while querying postponed messages");            return;        }        while (c.moveToNext()) {            String body = c.getString(1);            mAdaptee.sendMessageAsync(new Message(body));            c.updateLong(2, System.currentTimeMillis());            c.updateInt(3, Im.MessageType.OUTGOING);        }        c.commitUpdates();        c.close();    }    public void registerChatListener(IChatListener listener) {        if (listener != null) {            mListenerAdapter.addRemoteListener(listener);        }    }    public void unregisterChatListener(IChatListener listener) {        mListenerAdapter.removeRemoteListener(listener);    }    String getNickName(String username) {        ImEntity participant = mAdaptee.getParticipant();        if (mIsGroupChat) {            ChatGroup group = (ChatGroup)participant;            List<Contact> members = group.getMembers();            for (Contact c : members) {                if (username.equals(c.getAddress().getFullName())) {                    return c.getName();                }            }            // not found, impossible            return username;        } else {            return ((Contact)participant).getName();        }    }    void onConvertToGroupChatSuccess(ChatGroup group) {        Contact oldParticipant = (Contact)mAdaptee.getParticipant();        String oldAddress = getAddress();        mAdaptee.setParticipant(group);        mChatManager.updateChatSession(oldAddress, this);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -