Search Google

Friday 19 September 2014

how to make an android app like facebook,whatsapp

Sending Messages

 

http://blog.kii.com/?p=3380 

Once you have added friends to your friend’s list you can invite them to chat by tapping on them:


kiichat_chat
The chat setup is performed in ChatListFragment.NewChatTask: and basically adds the involved parties to a KiiGroup and creates a KiiTopic to channel the invitations to chat:
@Override
protected KiiGroup doInBackground(Void... params) {
  try {
    String chatRoomName = ChatRoom.getChatRoomName(KiiUser.getCurrentUser(), this.chatFriend);
    String uniqueKey = ChatRoom.getUniqueKey(KiiUser.getCurrentUser(), this.chatFriend);
    for (int i = 0; i < getListView().getCount(); i++) {
      KiiGroup kiiGroup = (KiiGroup)getListView().getItemAtPosition(i);
      if (TextUtils.equals(uniqueKey, ChatRoom.getUniqueKey(kiiGroup))) {
        return kiiGroup;
      }
    }
    KiiGroup kiiGroup = Kii.group(chatRoomName);
    KiiUser target = KiiUser.createByUri(Uri.parse(this.chatFriend.getUri()));
    target.refresh();
    kiiGroup.addUser(target);
    kiiGroup.save();
    KiiBucket chatBucket = ChatRoom.getBucket(kiiGroup);
    KiiUser.getCurrentUser().pushSubscription().subscribeBucket(chatBucket);
    KiiTopic topic = target.topicOfThisUser(ApplicationConst.TOPIC_INVITE_NOTIFICATION);
    Data data = new Data();
    data.put(ChatRoom.CHAT_GROUP_URI, kiiGroup.toUri().toString());
    KiiPushMessage message = KiiPushMessage.buildWith(data).build();
    topic.sendMessage(message);
    Logger.i("sent notification to " + target.toUri().toString());
    return kiiGroup;
  } catch (Exception e) {
    Logger.e("failed to start chat", e);
    return null;
  }
}
In the above code you can see that a ChatRoom is matched to a KiiGroup. Then the target user (the one that will be contacted) is added to the group. A group scope bucket is used here to hold the messages sent by the users and the current user is subscribed to receive push notifications from it (all subscribed users to the group bucket will receive a notification when a new message is posted). Finally a message is built with the chat group URI to notify the target user of the invitation.
In the code above we don’t see any low level configuration of push notifications. However this is done as soon as a user registers or signs in. In the “User Registration and Login” section we described how a user was coupled to ChatUser during an initialization process performed in ChatUserInitializeTask.initializeChatUser(). That method also initializes the push notification system so users can send/receive messages. Let’s take a closer look at the code:
KiiUser kiiUser = KiiUser.getCurrentUser();
ChatUser user = ChatUser.findByUri(kiiUser.toUri());
if (user == null) {
  user = new ChatUser(kiiUser.toUri().toString(), username, email);
  user.getKiiObject().save();
}
KiiUser.pushInstallation().install(GCMUtils.register());
KiiTopic topic = KiiUser.topic(ApplicationConst.TOPIC_INVITE_NOTIFICATION);
try {
  topic.save();
} catch (ConflictException e) {
}
KiiACL acl = topic.acl();
acl.putACLEntry(new KiiACLEntry(KiiAnyAuthenticatedUser.create(), TopicAction.SEND_MESSAGE_TO_TOPIC, true));
try {
  acl.save();
} catch (ACLOperationException e) {
  Throwable t = e.getCause();
  if (!(t instanceof ConflictException)){
    throw e;
  }
}
KiiPushSubscription subscription = kiiUser.pushSubscription();
try {
  subscription.subscribe(topic);
} catch (ConflictException e) {
}
kiiUser.set(INITIALIZED_USER_KEY, true);
kiiUser.update();
As you can see above push notifications are initialized for the current user, a KiiTopic is created to receive invite notifications and its permissions are changed to allow any registered user to send an invitation. Finally the current user is subscribed to the topic so it can receive invitations.
This set the stage for the interchange of user messages. The class ChatActivity encapsulates all the chat interaction itself. Let’s take a look at the code called when the “Send” message button is clicked:
this.btnSend.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    btnSend.setEnabled(false);
    final ChatMessage message = new ChatMessage(kiiGroup);
    message.setMessage(editMessage.getText().toString());
    message.setSenderUri(KiiUser.getCurrentUser().toUri().toString());
    new SendMessageTask(message).execute();
  }
});
In the code above a ChatMessage is initialized on a the current user group, the message text is grabbed from the UI text box and the sender is set to the current user. Let’s take a look at the SendMessageTask main background method:
  @Override
  protected Boolean doInBackground(Void... params) {
    try {
      this.message.getKiiObject().save();
      ChatStamp.sendUsageEvent(this.message);
      return true;
    } catch (Exception e) {
      Logger.e("failed to send messsage", e);
      return false;
    }
Here the message is saved in the backend triggering a modification in the user group associated with it. All group members will get a push notification when this happens. Note that an analytics event is also sent (for detail see ChatStamp.sendUsageEvent()). Kii Cloud can aggregate this type of events (and also any stored data) to later offer you the chance to create metrics and slice and dice the information (with advanced visualization) from a convenient web console.
To wrap-up this section let’s review some of the details of how to receive this message notifications. In order to detect incoming push notification an Android BroadcastReceiver is set up:
private final BroadcastReceiver handleMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    updateMessage(false);
  }
};

private void updateMessage(boolean showProgress) {
  new GetMessageTask(showProgress).execute();
}
And GetMessageTask‘s main background process refreshes the list of messages (including the incoming one) using a ChatRoom that is associated to the relevant group:
@Override
protected List<ChatMessage> doInBackground(Void... params) {
  try {
    ChatRoom chatRoom = new ChatRoom(kiiGroup);
    List<ChatMessage> messages = null;
    if (lastGotTime == null) {
      messages = chatRoom.getMessageList();
    } else {
      messages = chatRoom.getMessageList(lastGotTime);
    }
    if (messages.size() > 0) {
      lastGotTime = messages.get(messages.size() - 1).getKiiObject().getCreatedTime();
    }
    return messages;
  } catch (Exception e) {
    Logger.e("failed to get message", e);
    return null;
  }
}

Sending Photos (Stamps)

With Kii Cloud it’s very easy to attach a files to objects that you save in the backend (you just upload/download them as object bodies). Here’s a screenshot of two friends sharing images:
kiichat_stamps

No comments:

Post a Comment