Quickblox Android SDK群组聊天

用户名

我正在使用quickblox sdk群聊。这是我的代码。但是我还是错的。有人可以指导我吗?

UserListForGroupActivity.java

公共类UserListForGroupActivity扩展Activity实现QBCallback {

private ListView usersList;
private ProgressDialog progressDialog;
private Button btnChat;
private SimpleAdapter usersAdapter;
private ArrayList<Friend_Users> friends= new ArrayList<Friend_Users>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_list_for_group);

    usersList = (ListView) findViewById(R.id.usersList);
    btnChat=(Button)findViewById(R.id.btnstartGroupChat);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading fiends list");
    progressDialog.show();

    // ================= QuickBlox ===== Step 4 =================
    // Get all users of QB application.
    QBUsers.getUsers(this);

}

@Override
public void onComplete(Result result) {
    if (result.isSuccess()) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }

        // Cast 'result' to specific result class QBUserPagedResult.
        QBUserPagedResult pagedResult = (QBUserPagedResult) result;
        final ArrayList<QBUser> users = pagedResult.getUsers();
        System.out.println(users.toString());
        // Prepare users list for simple adapter.
        ArrayList<Map<String, String>> usersListForAdapter = new ArrayList<Map<String, String>>();
        for (QBUser u : users) {
            Map<String, String> umap = new HashMap<String, String>();
            umap.put("userLogin", u.getLogin());
            umap.put("chatLogin", QBChat.getChatLoginFull(u));
            usersListForAdapter.add(umap);
        }

        // Put users list into adapter.
         usersAdapter = new SimpleAdapter(this, usersListForAdapter,
                android.R.layout.simple_list_item_multiple_choice,
                new String[]{"userLogin", "chatLogin"},
                new int[]{android.R.id.text1, android.R.id.text2});
        usersList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        usersList.setAdapter(usersAdapter);

       btnChat.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                SparseBooleanArray checked= usersList.getCheckedItemPositions();
                for (int i = 0; i < checked.size(); i++) {
                    // Item position in adapter
                    int position = checked.keyAt(i);
                    // Add sport if it is checked i.e.) == TRUE!
                    if (checked.valueAt(i))
                    {
                        QBUser friendUser = users.get(position);
                        String login, password;
                        int id;
                        id=friendUser.getId();
                        login=friendUser.getLogin();
                        password=friendUser.getPassword();
                        friends.add(new Friend_Users(id,login, password));
                    }
                }
                Friend_Users_Wrapper wrapper= new Friend_Users_Wrapper(friends);
                Log.e("UserListForGroupAcitvity friend list pass intent=>", friends.size()+ friends.get(0).getLogin());
                Bundle extras = getIntent().getExtras();

                Intent intent=new Intent(UserListForGroupActivity.this, GroupChatActivity.class);
                intent.putExtra("friends", wrapper);                
                intent.putExtras(extras);
                startActivity(intent);

            }
        });

    } else {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("Error(s) occurred. Look into DDMS log for details, " +
                "please. Errors: " + result.getErrors()).create().show();
    }
}


@Override
public void onComplete(Result result, Object context) { }

}

GroupChatActivity.java

公共类GroupChatActivity扩展Activity {

private EditText messageText;
private TextView meLabel;
private TextView friendLabel;
private ViewGroup messagesContainer;
private ScrollView scrollContainer;
private QBUser me;
private GroupChatController groupChatController;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);

    // Load QBUser objects from bundle (passed from previous activity).
    Bundle extras = getIntent().getExtras();

    Friend_Users_Wrapper wrapper= (Friend_Users_Wrapper) getIntent().getSerializableExtra("friends"); 
    ArrayList<Friend_Users> friendArray= wrapper.getFriend_Users();
    me = new QBUser();
    me.setId(extras.getInt("myId"));
    me.setLogin(extras.getString("myLogin"));
    me.setPassword(extras.getString("myPassword"));
    System.out.println("user login =>"+extras.getString("myLogin"));
    QBUser friends= new QBUser();
    for (Friend_Users friend_Users : friendArray) {
        friends.setId(friend_Users.getId());
        friends.setLogin(friend_Users.getLogin());
        friends.setPassword(friend_Users.getPassword());
    }



    // UI stuff
    messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
    scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);

    Button sendMessageButton = (Button) findViewById(R.id.sendButton);
    sendMessageButton.setOnClickListener(onSendMessageClickListener);

    messageText = (EditText) findViewById(R.id.messageEdit);

    // ================= QuickBlox ===== Step 5 =================
    // Get chat login based on QuickBlox user account.
    // Note, that to start chat you should use only short login,
    // that looks like '17744-1028' (<qb_user_id>-<qb_app_id>).
    String chatLogin = QBChat.getChatLoginShort(me);

    // Our current (me) user's password.
    String password = me.getPassword();    

    if (me != null && friends != null) {


        // ================= QuickBlox ===== Step 6 =================
        // All chat logic can be implemented by yourself using
        // ASMACK library (https://github.com/Flowdalic/asmack/downloads)
        // -- Android wrapper for Java XMPP library (http://www.igniterealtime.org/projects/smack/).
        groupChatController = new GroupChatController(chatLogin, password);
        groupChatController.setOnMessageReceivedListener(onMessageReceivedListener);

        // ================= QuickBlox ===== Step 7 =================
        // Get friend's login based on QuickBlox user account.
        // Note, that for your companion you should use full chat login,
        // that looks like '[email protected]' (<qb_user_id>-<qb_app_id>@chat.quickblox.com).
        // Don't use short login, it
        String friendLogin = QBChat.getChatLoginFull(friends);

        groupChatController.startChat(friendLogin);
    }
}

private void sendMessage() {
    if (messageText != null) {
        String messageString = messageText.getText().toString();
        groupChatController.sendMessage(messageString);
        messageText.setText("");
        showMessage(me.getLogin() + " (me) : "+messageString, true);
    }
}

private GroupChatController.OnMessageReceivedListener onMessageReceivedListener = new GroupChatController.OnMessageReceivedListener() {
    @Override
    public void onMessageReceived(final Message message) {
        String messageString = message.getBody();
        showMessage(messageString, false);
    }
};

private void showMessage(String message, boolean leftSide) {
    final TextView textView = new TextView(GroupChatActivity.this);
    textView.setTextColor(Color.BLACK);
    textView.setText(message);

    int bgRes = R.drawable.left_message_bg;

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    if (!leftSide) {
        bgRes = R.drawable.right_message_bg;
        params.gravity = Gravity.RIGHT;
    }

    textView.setLayoutParams(params);

    textView.setBackgroundResource(bgRes);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            messagesContainer.addView(textView);

            // Scroll to bottom
            if (scrollContainer.getChildAt(0) != null) {
                scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
            }
            scrollContainer.fullScroll(View.FOCUS_DOWN);
        }
    });
}

private View.OnClickListener onSendMessageClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        sendMessage();
    }
};

}

GroupChatController.java

公共类GroupChatController {

// Get QuickBlox chat server domain.
// There will be created connection with chat server below.
public static final String CHAT_SERVER = QBChat.getChatServerDomain();

private XMPPConnection connection;

private ConnectionConfiguration config;

private Chat chat;
// Multi-User Chat
private MultiUserChat muc2;

private String chatLogin;
private String password;
private String friendLogin;

private ChatManager chatManager;

public GroupChatController(String chatLogin, String password) {
    this.chatLogin = chatLogin;
    this.password = password;
}

public void startChat(String buddyLogin) {
    this.friendLogin = buddyLogin;

    new Thread(new Runnable() {
        @Override
        public void run() {
            // Chat action 1 -- create connection.
            Connection.DEBUG_ENABLED = true;
            config = new ConnectionConfiguration(CHAT_SERVER);
            connection = new XMPPConnection(config);

            try {
                connection.connect();
                connection.login(chatLogin, password);

                // Chat action 2 -- create chat manager.
                chatManager = connection.getChatManager();

                // Chat action 3 -- create chat.
                chat = chatManager.createChat(friendLogin, messageListener);

                // Set listener for outcoming messages.
                chatManager.addChatListener(chatManagerListener);

                // Muc 2 
                if(connection != null){
                    muc2 = new MultiUserChat(connection, "[email protected]");
                    // Discover whether [email protected] supports MUC or not

                    // The room service will decide the amount of history to send
                    muc2.join(chatLogin);
                    muc2.invite(friendLogin, "Welcome!");
                    Log.d("friendLogin ->",friendLogin);

                    // Set listener for outcoming messages.
                    //chatManager.addChatListener(chatManagerListener);
                    muc2.addMessageListener(packetListener);
                    addListenerToMuc(muc2);
                    //[email protected]
                }

                Message message = new Message(friendLogin + "@muc.chat.quickblox.com");
                message.setBody("Join me for a group chat!");
                message.addExtension(new GroupChatInvitation("[email protected]"));
                connection.sendPacket(message);

            } catch (XMPPException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

/*** muc */
private void addListenerToMuc(MultiUserChat muc){
    if(null != muc){
        muc.addMessageListener(new PacketListener() {
            @Override
            public void processPacket(Packet packet) {
                Log.i("processPacket", "receiving message");
            }
        });
    }
}    

PacketListener packetListener = new PacketListener() {
    @Override
    public void processPacket(Packet packet) {
      Message message = (Message)packet;
      try {
      muc2.sendMessage(message);
  } catch (XMPPException e) {
      e.printStackTrace();
  }
      //System.out.println("got message " + message.toXML());
    }
};  

private PacketInterceptor packetInterceptor = new PacketInterceptor() {

    @Override
    public void interceptPacket(Packet packet) {
         System.out.println("Sending message: " + packet.toString());
         Message message = muc2.createMessage();
         message.setBody("Hello from producer, message " +
                " ");
         try {
            muc2.sendMessage(message);
        } catch (XMPPException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
};

/***/
private ChatManagerListener chatManagerListener = new ChatManagerListener() {
    @Override
    public void chatCreated(Chat chat, boolean createdLocally) {
        // Set listener for incoming messages.
        chat.addMessageListener(messageListener);
        muc2.addMessageListener(packetListener);
    }
};

public void sendMessage(String message) {
    try {
        if (chat != null) {
            chat.sendMessage(message);
        }
        if (muc2 != null) {
            muc2.sendMessage(message);
        }
    } catch (XMPPException e) {
        e.printStackTrace();
    }
}

private MessageListener messageListener = new MessageListener() {
    @Override
    public void processMessage(Chat chat, Message message) {
        // 'from' and 'to' fields contains senders ids, e.g.
        // [email protected]/mac-167
        // [email protected]/Smack
        String from = message.getFrom().split("@")[0];
        String to = message.getTo().split("@")[0];

        System.out.println(String.format(">>> Message received (from=%s, to=%s): %s",
                from, to, message.getBody()));

        if (onMessageReceivedListener != null) {
            onMessageReceivedListener.onMessageReceived(message);
        }
    }
};


public static interface OnMessageReceivedListener {
    void onMessageReceived(Message message);
}

// Callback that performs when device retrieves incoming message.
private OnMessageReceivedListener onMessageReceivedListener;

public OnMessageReceivedListener getOnMessageReceivedListener() {
    return onMessageReceivedListener;
}

public void setOnMessageReceivedListener(OnMessageReceivedListener onMessageReceivedListener) {
    this.onMessageReceivedListener = onMessageReceivedListener;
}

}

安德鲁·迪米特连科(Andrew Dmytrenko)
public void startChat(String buddyLogin) {
...
List<String> usersLogins= new ArrayList<String>();
    for(String userLogin: usersLogins){
        muc2.invite(userLogin, "Welcome!");   
    }
...

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

登录QuickBlox for Android应用中的聊天

来自分类Dev

Quickblox聊天应用程序,Android

来自分类Dev

无法解析:com.quickblox:quickblox-android-sdk-core:3.0.0 和无法解析:com.quickblox:quickblox-android-sdk-chat:3.0.0

来自分类Dev

Quickblox android API是否免费提供聊天消息?

来自分类Dev

每个对象在Quickblox Android私人聊天中的功能是什么?

来自分类Dev

QuickBlox 2.0聊天对话框-如何检测用户加入或离开群组聊天对话框?

来自分类Dev

QuickBlox聊天未登录

来自分类Dev

Quickblox Android SDK 2.0 Beta缺少某些类

来自分类Dev

从quickblox android下载图像

来自分类Dev

Quickblox Chat Application,Android

来自分类Dev

QuickBlox Android NoResponse

来自分类Dev

无法使用QuickBlox Javascript SDK发送聊天消息

来自分类Dev

Quickblox聊天消息读取状态

来自分类Dev

Quickblox无法发送消息聊天

来自分类Dev

Quickblox聊天消息读取状态

来自分类Dev

Quickblox聊天数据复制

来自分类Dev

在Quickblox中动态更新聊天

来自分类Dev

Android quickblox公共聊天对话框的乘员ID为null

来自分类Dev

Android quickblox如果用户不在聊天室中如何接收消息

来自分类Dev

Quickblox通知聊天室IOS中的自定义参数到Android

来自分类Dev

来自Quickblox的示例视频聊天在Android中不起作用

来自分类Dev

14之前,QuickBlox Android SDK 1.2不再在Android API上运行

来自分类Dev

无法在Android中登录QuickBlox

来自分类Dev

只有群组中的每个人都已阅读邮件后,才有办法让邮件在quickblox群组聊天中具有阅读状态

来自分类Dev

Quickblox:找不到SDK位置

来自分类Dev

Quickblox -SDK for Android App在后台运行时无法接听电话

来自分类Dev

将我的联系人与quickblox同步,并为Android中的自定义聊天应用程序检索这些用户

来自分类Dev

QuickBlox聊天消息侦听器

来自分类Dev

使用QuickBlox保存聊天记录

Related 相关文章

  1. 1

    登录QuickBlox for Android应用中的聊天

  2. 2

    Quickblox聊天应用程序,Android

  3. 3

    无法解析:com.quickblox:quickblox-android-sdk-core:3.0.0 和无法解析:com.quickblox:quickblox-android-sdk-chat:3.0.0

  4. 4

    Quickblox android API是否免费提供聊天消息?

  5. 5

    每个对象在Quickblox Android私人聊天中的功能是什么?

  6. 6

    QuickBlox 2.0聊天对话框-如何检测用户加入或离开群组聊天对话框?

  7. 7

    QuickBlox聊天未登录

  8. 8

    Quickblox Android SDK 2.0 Beta缺少某些类

  9. 9

    从quickblox android下载图像

  10. 10

    Quickblox Chat Application,Android

  11. 11

    QuickBlox Android NoResponse

  12. 12

    无法使用QuickBlox Javascript SDK发送聊天消息

  13. 13

    Quickblox聊天消息读取状态

  14. 14

    Quickblox无法发送消息聊天

  15. 15

    Quickblox聊天消息读取状态

  16. 16

    Quickblox聊天数据复制

  17. 17

    在Quickblox中动态更新聊天

  18. 18

    Android quickblox公共聊天对话框的乘员ID为null

  19. 19

    Android quickblox如果用户不在聊天室中如何接收消息

  20. 20

    Quickblox通知聊天室IOS中的自定义参数到Android

  21. 21

    来自Quickblox的示例视频聊天在Android中不起作用

  22. 22

    14之前,QuickBlox Android SDK 1.2不再在Android API上运行

  23. 23

    无法在Android中登录QuickBlox

  24. 24

    只有群组中的每个人都已阅读邮件后,才有办法让邮件在quickblox群组聊天中具有阅读状态

  25. 25

    Quickblox:找不到SDK位置

  26. 26

    Quickblox -SDK for Android App在后台运行时无法接听电话

  27. 27

    将我的联系人与quickblox同步,并为Android中的自定义聊天应用程序检索这些用户

  28. 28

    QuickBlox聊天消息侦听器

  29. 29

    使用QuickBlox保存聊天记录

热门标签

归档