2

私は、quickblox SDK グループ チャットを使用しています。これは私のコードです。しかし、私はまだ間違っています。誰でも私を案内してもらえますか?

UserListForGroupActivity.java

public class UserListForGroupActivity extends Activity implement 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

public class GroupChatActivity extends 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 '17792-1028@chat.quickblox.com' (<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

public class 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, "2389_chat1@muc.chat.quickblox.com");
                    // Discover whether user3@host.org 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);
                    //chat1@muc.chat.quickblox.com
                }

                Message message = new Message(friendLogin + "@muc.chat.quickblox.com");
                message.setBody("Join me for a group chat!");
                message.addExtension(new GroupChatInvitation("2389_chat1@muc.chat.quickblox.com"));
                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.
        // 17792-1028@chat.quickblox.com/mac-167
        // 17744-1028@chat.quickblox.com/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;
}

}

4

1 に答える 1