Android ADD FRIEND using Smack - android

I am new to the use of smack library and making one chatting application. I have made upto much extent and at this step i want to ask two questions.
when i add a friend the friend got added in my list but there is not any notification sent to the FRIEND whom i have added, How to achieve the same. I have added the code below.
The second thing i want to ask is that how can I check whether the user which I am going to add is a part or member of the app or not ( mean it is on the server or not). So that the user who is not registered to the app should not be added in the friends list.
here is the code
public static boolean addFriend(String jid) {
String nickname = null;
nickname = StringUtils.parseBareAddress(jid);
RosterEntry entry4 = roster.getEntry("samsad");
if (!roster.contains(jid)) {
try {
Presence subscribe = new Presence(Presence.Type.subscribe);
subscribe.setTo(jid);
connection.sendPacket(subscribe);
roster.createEntry(jid, nickname, null);
// Send a roster entry (any) to user2
RosterExchangeManager REM = new RosterExchangeManager(connection);
REM.send(entry4, jid);
return true;
} catch (XMPPException e) {
System.err.println("Error in adding friend");
return false;
}
} else {
return false;
}
}
Roster Exchange manager running in the service in background
/**Remotr Exchange Manager*/
RosterExchangeManager rem = new RosterExchangeManager(connection);
// Create a RosterExchangeListener that will iterate over the received roster entries
RosterExchangeListener rosterExchangeListener = new RosterExchangeListener() {
public void entriesReceived(String from, Iterator remoteRosterEntries) {
notification("Receive==4");
while (remoteRosterEntries.hasNext()) {
try {
// Get the received entry
RemoteRosterEntry remoteRosterEntry = (RemoteRosterEntry) remoteRosterEntries.next();
// Display the remote entry on the console
System.out.println(remoteRosterEntry);
// Add the entry to the user2's roster
roster.createEntry(
remoteRosterEntry.getUser(),
remoteRosterEntry.getName(),
remoteRosterEntry.getGroupArrayNames());
notification("Receive==1");
}
catch (XMPPException e) {
e.printStackTrace();
}
}
}
};
rem.addRosterListener(rosterExchangeListener);
}
else{
showToast("Connection lost-",0);
}
}

1, The problem is you must register a PacketListener for Presence.Type.subscribe before you connect to server. All the process of add and accept friend i answered in here
2, You can use UserSearch class to search for a specific user and if user is not found on server then you can assume that user is not registered on server.

Related

XMPP - Using lib Smack remove user from group(conference) in MUC

We are integrating MUC in our app for group chat. where we can create group(conference) and adding members. Questions are-
Removed member still getting group messages. What is proper way of remove a member from group?
How to get total members of group (online/offline)?
We are using following methods to remove a members-
public void kickOutRoomMember(String groupJid, String memberNickName) {
MultiUserChat muc;
try {
if (manager == null) {
manager = MultiUserChatManager.getInstanceFor(connection);
}
muc = manager.getMultiUserChat(groupJid);
muc.kickParticipant(memberNickName, "");
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeOutRoomMember(String groupJid, String memberNickName) {
MultiUserChat muc;
try {
if (manager == null) {
manager = MultiUserChatManager.getInstanceFor(connection);
}
muc = manager.getMultiUserChat(groupJid);
muc.banUser(memberNickName, "");
} catch (Exception e) {
e.printStackTrace();
}
}
Theorically you are right.
Just check
If user who invokes banUser has grants to do it
to pass bare
jid and not memberNickName as first parameter in method.
javadoc
muc.banUser("Mickey Mouse", ""); //does not works
muc.banUser("mickeymouse#server","") // will works
Install "Rest API" plugin.
Rest API plugin provides all the API related group. Create Or delete a group, Add or remove a member from a group, get all members of group etc..

How to add users to a roster in xmpp?

I have successfully created a user using the following code:
accountmanager = new org.jivesoftware.smack.AccountManager(connection);
accountmanager.createAccount(fbuserid,fbuserid);
But I am not able to add other users to the logged in user's roster using the following code :
public void createEntry(String user, String name, String[] groups) throws XMPPException {
// Create and send roster entry creation packet.
RosterPacket rosterPacket = new RosterPacket();
rosterPacket.setType(IQ.Type.SET);
RosterPacket.Item item = new RosterPacket.Item(user, name);
if (groups != null) {
for (String group : groups) {
if (group != null) {
item.addGroupName(group);
}
}
}
rosterPacket.addRosterItem(item);
// Wait up to a certain number of seconds for a reply from the server.
PacketCollector collector = connection.createPacketCollector(
new PacketIDFilter(rosterPacket.getPacketID()));
connection.sendPacket(rosterPacket);
IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
if (response == null) {
throw new XMPPException("No response from the server.");
}
// If the server replied with an error, throw an exception.
else if (response.getType() == IQ.Type.ERROR) {
throw new XMPPException(response.getError());
}
// Create a presence subscription packet and send.
Presence presencePacket = new Presence(Presence.Type.subscribe);
presencePacket.setTo(user);
connection.sendPacket(presencePacket);
}
I am always getting the response as null. Someone please help me to solve this and Thanks in advance
Rosters and presence use a permissions-based model where users must give permission before they are added to someone else's roster. This protects a user's privacy by making sure that only approved users are able to view their presence information. Therefore, when you add a new roster entry it will be in a pending state until the other user accepts your request.
If another user requests a presence subscription so they can add you to their roster, you must accept or reject that request. Smack handles presence subscription requests in one of three ways:
Automatically accept all presence subscription requests.
Automatically reject all presence subscription requests.
Process presence subscription requests manually. The mode can be set using the
Roster.setSubscriptionMode(Roster.SubscriptionMode) method. Simple clients normally use one of the automated subscription modes, while full-featured clients should manually process subscription requests and let the end-user accept or reject each request. If using the manual mode, a PacketListener should be registered that listens for Presence packets that have a type of Presence.Type.subscribe.
Try this in code first to add user in roster as well as requesting the users permission.
roster = Roster.getInstanceFor(connection);
if (!roster.isLoaded())
try {
roster.reloadAndWait();
} catch (SmackException.NotLoggedInException e) {
Log.i(TAG, "NotLoggedInException");
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
Log.i(TAG, "NotConnectedException");
e.printStackTrace();
}
roster.createEntry(jID, name, null);
On other user side/ in your code after login from one user:
roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
To make user status online:
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("Online, Programmatically!");
presence.setPriority(24);
presence.setMode(Presence.Mode.available);
roster = Roster.getInstanceFor(connection);

Android xmpp MUC setting default configuration

Am using the Xabber open source project and am able to create a new group, But it always says: This room is locked from entry until configuration is confirmed. I tried to set a default configuration but it throws me exception: 401 not authorized. Whats exactly the problem.
final MultiUserChat multiUserChat;
try {
multiUserChat = new MultiUserChat(xmppConnection, room);
// CHANAKYA: set default config for the MUC
// Send an empty room configuration form which indicates that we want
// an instant room
try {
multiUserChat.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
} catch (XMPPException e) {
e.printStackTrace();
}
I was also facing the same error. Here I modified the code and it's work for me.
Error 401 is not authorized error when we are calling the any getConfigurationForm(), without joining it.
multiUserChat.join(nickname, password);
setConfig(multiUserChat); // Here I am calling submit form
private void setConfig(MultiUserChat multiUserChat) {
try {
Form form = multiUserChat.getConfigurationForm();
Form submitForm = form.createAnswerForm();
for (Iterator<FormField> fields = submitForm.getFields(); fields
.hasNext();) {
FormField field = (FormField) fields.next();
if (!FormField.Type.hidden.equals(field.getType())
&& field.getVariable() != null) {
submitForm.setDefaultAnswer(field.getVariable());
}
}
submitForm.setAnswer("muc#roomconfig_publicroom", true);
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
multiUserChat.sendConfigurationForm(submitForm);
} catch (Exception e) {
e.printStackTrace();
}
}
And now I am able to successfully submit the form without any exception. Hope this will work for you.
You must have permissions to set the configuration. This can usually be changed in the server settings. If you have Openfire for example you should go to Group Chat>Group chat settings>Click your Group Chat service>Room Creation Permissions or Administrators.
You are probably unable to change this client side, it's only possible if you have access to the server you are trying to connect to.

Delete a Friend from Roster in Xmpp/Openfire

In my chat application. I am using smack library , with the help of Subscription Management I have done the part of adding a friend to the Roster of a particular person.
Now I want that when some person denies the friend request, I send a UNSUBSCRIBE PACKET to the other user for the same, the friend is not deleted from the roster of the other user. It simply shows NONE subscription.
CODE:
Presence unsubscribe = new Presence(Presence.Type.unsubscribe);
unsubscribe.setTo(ABC#ABC.COM);
connection.sendPacket(unsubscribe);
How can I delete the user from the Roster of the friend. I can do it from openfire portal but don't know how to do it from code.
From the Smack forum, this code might work:
RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET);
RosterPacket.Item item = new RosterPacket.Item("ABC#ABC.COM", null);
item.setItemType(RosterPacket.ItemType.REMOVE);
packet.addRosterItem(item);
connection.sendPacket(packet);
This code worked for me
if(selectedRoster != null) {
Presence presence = new Presence(Presence.Type.unsubscribe);
presence.setTo(selectedRoster.getUser());
presence.setStatus("Offline");
presence.setShow("unavailable");
ConnectionController.GetInstance(this).getXMPPConnection().sendPacket(presence);
try {
roster.removeEntry(selectedRoster);
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

How to Add and Subscribe a jabber entry to my XMPP Account?

I am able to add Entry to the Xmpp account by using this code. i can't get subscription "both", instead of this i am getting none.
roster.createEntry("abc#xyz.com", "abc", null);
How to add entry with the presence type=both, when i am subscribing entry to this account. I want to know whether xmpp publish-subscribe functionality ?
How to get Inbound presence notifications ?
How to send Outbound presence notifications ?
EDIT :
public void Addcontact() {
Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
Roster roster = m_connection.getRoster();
if(!roster.contains("pa#ace.com")) { try {
roster.createEntry("pa#ace.com", "pa", null);
} catch (XMPPException e) {
e.printStackTrace();
}
}else {
Log.i("Acc = ", "contains");
}
}
I am adding entry like this still i am getting Presence Type = none..
Here is how I add another friend in my application.
protected void doAddContactToListAsync(String address, String name,
ContactList list) throws ImException {
debug(TAG, "add contact to " + list.getName());
Presence response = new Presence.Type.subscribed);
response.setTo(address);
sendPacket(response);
Roster roster = mConnection.getRoster();
String[] groups = new String[] { list.getName() };
if (name == null) {
name = parseAddressName(address);
}
try {
roster.createEntry(address, name, groups);
// If contact exists locally, don't create another copy
Contact contact = makeContact(name, address);
if (!containsContact(contact))
notifyContactListUpdated(list,
ContactListListener.LIST_CONTACT_ADDED, contact);
else
debug(TAG, "skip adding existing contact locally " + name);
} catch (XMPPException e) {
throw new RuntimeException(e);
}
}
Just use the essential part
Presence response = new Presence.Type.subscribed);
response.setTo(address);
sendPacket(response);
Roster roster = mConnection.getRoster();
roster.createEntry(address, name, groups);
In order to listen to incoming request, register addPacketListener to your connection
mConnection.addPacketListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Presence presence = (Presence) packet;
if (presence.getType() == Type.subscribe) {
debug(TAG, "sub request from 1" + address);
//Implement accept or reject depend on user action.
mContactListManager.getSubscriptionRequestListener()
.onSubScriptionRequest(contact);
//or you can test with send back Presence.subscribe first and send Presence.subscribed back to requester.
} else {// Handle other Presence type.
int type = parsePresence(presence);
debug(TAG, "sub request from " + type);
contact.setPresence(new Presence(type,
presence.getStatus(), null, null,
Presence.CLIENT_TYPE_DEFAULT));
}
}
}, new PacketTypeFilter(Presence.class));
mConnection.connect();
The right order:
User1 send Subscribe to user2.
User2 send Subscribe and Subsribed back to user1.
User1 send Subsribed to user2.
Another SO question you can check

Categories

Resources