how to implement smack for xmpp - android

I'm trying to have my android app to be able to send and receive xmpp message using smack but it does not work and the connect command does not return. I have seen several code example but Smack has new versions and the syntax has changed so I might be doing something wrong :
in my build.graddle file I use :
compile "org.igniterealtime.smack:smack-android-extensions:4.3.0"
compile "org.igniterealtime.smack:smack-tcp:4.3.0"
I'm trying to send a message from myaccount321#xabber.org to myaccount456#xabber.org
I'm trying to connect using hot-chilli.net (Idon't mind using some other server))
everything seems to go well until connection.connect() after which the script does not return without triggering any exception.
Please tell me what I'm doing wrong
TIA
public void sendxmpp(){
XMPPTCPConnectionConfiguration config = null;
try {
XMPPTCPConnectionConfiguration.Builder configbuilder = XMPPTCPConnectionConfiguration.builder();
configbuilder.setUsernameAndPassword("myaccount321","myaccount321pw");
DomainBareJid serviceName = JidCreate.domainBareFrom("hot-chilli.net");
configbuilder.setServiceName(serviceName);
configbuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
configbuilder.setHost("jabber.hot-chilli.net");
configbuilder.setPort(8222);
config=configbuilder.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect();
}
catch (SmackException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (XMPPException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
connection.login();
ChatManager chatManager = ChatManager.getInstanceFor(connection);
EntityBareJid jid = JidCreate.entityBareFrom("myaccount321pw#xabber.org");
Chat chat = chatManager.createChat(jid);
chat.sendMessage("Hello");
}
catch (Exception e) {
}
}

OK I got it, the connection process has to be done in its own thread.

Related

Android XMPPTCPConnection: Machine is not on the network

While on Wifi, XMPPTCPConnection in our Android app is occasionally throwing "SocketException: Machine is not on the network" even though the phone does have net connection. When users turns off Wifi and turns it on again, the app is able to connect instantly.
When this exception occurs, the XMPPTCPConnection object is disconnected and set to NULL and created afresh before attempting reconnection. Yet it does not help. Below is the code snippet.
try {
if (null != connection)
connection.disconnect();
} catch (Exception e) {
}
connection = null;
XMPPTCPConnectionConfiguration connConfig = createConfiguration();
if (null != connConfig)
{
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (StackOverflowError e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Please let me know how to fix this issue. Appreciate your help.
This is the stack trace.
org.jivesoftware.smack.SmackException$ConnectionException: The following addresses failed: '.com:5223' failed because java.net.SocketException: Machine is not on the network
at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectUsingConfiguration(XMPPTCPConnection.java:596)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectInternal(XMPPTCPConnection.java:830)
at org.jivesoftware.smack.AbstractXMPPConnection.connect(AbstractXMPPConnection.java:360)
at com.sarkms.cclib.XMPPConnLib.connectToChatServer(XMPPConnLib.java:184)
at com.sarkms.cclib.XMPPConnHelper.connectToChatServer(XMPPConnHelper.java:331)
at com.sarkms.cclib.XMPPConnHelper.LoginToChatServer(XMPPConnHelper.java:383)
at com.sarkms.cclib.ConnChkRun.runConnectionCheck(ConnChkRun.java:83)
at com.sarkms.cclib.ops.Connection.runConnection(Connection.java:142)
at com.sarkms.cclib.MessageService$1.run(MessageService.java:39)

SMACK 4.1 Account manager: Private Access Error in account registration

I am getting a strange error while working with account manager in Smack 4.1 for android.
Below is the code snippet:
am = new AccountManager(connection);
Map<String, String> mp = new HashMap<String, String>();
// adding or set elements in Map by put method key and value
// pair
mp.put("username", "user3");
mp.put("password", "ps3");
mp.put("name", "user3");
mp.put("email", "user3#user.com");
try {
am.createAccount("user3", "user3", mp);
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
The code I've used to connect to Openfire Server is:
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setServiceName("host_name");
configBuilder.setHost("host_name");
configBuilder.setPort(5222);
configBuilder.setCompressionEnabled(false).build();
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
try {
System.out.println("connecting");
connection.setPacketReplyTimeout(10000);
connection.connect();
System.out.println("connected");
SASLAuthentication.unBlacklistSASLMechanism("PLAIN");
SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
and is running perfect.
The exact error is: "Error:(66, 18) error: AccountManager(XMPPConnection) has private access in AccountManager"
I've wasted like 2-3 hours trying to find it but got no answers. I'm a noob so please forgive me if this is a basic question. Also please reply on that as I am stuck and can not move forward.
Thanks alot for the time!!
You need to get an instance from the accountManager that's relevant to your Xmpp connection.
AccountManager ac = AccountManager.getInstance(XMPPConnection connection)

Integrating Smack 4.1 in android

I have gone through smack 4.1 documentation as given https://github.com/igniterealtime/Smack/tree/master/documentation . But I'm not getting connected when try to connect to openfire server. Can anyone give me a working code. My openfire configuration is working. I have checked it using mac IM client.
I had the same issue when I tried exactly as in documentation.
But I found some changes needed after a research. Here is the code that I've used.
public void connect() throws IOException, XMPPException, SmackException {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setUsernameAndPassword("username","password");
config.setServiceName(Config.XMPP_DOMAIN);
config.setHost(Config.XMPP_HOST);
config.setPort(Config.XMPP_PORT);
mConnection = new XMPPTCPConnection(config.build());
try {
mConnection.connect();
mConnection.login();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
//ChatManager.getInstanceFor(mConnection).addChatListener(this);
}
check out the link working example http://developer.samsung.com/technical-doc/view.do?v=T000000119

Android application is freezed - Socket Exception

I made android application that connects to remote server and send some data.
Remote server is Windows application.
Connection method:
private void ConnectToMonitor() {
try {
s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This works perfectly if server is online. Application is sending data and server is receiving. But if server is offline android app. is blocked. My question is how to handle this? How to continue with application and avoid error even the server is down?
Remember to call this outside the UIThread.
Follow this tutorial. In android all connections need to be managed outside the UIThread, in the tutorial I linked you will find easy ways to post your results back to the UI (handlers, asynctasks...)
Of course we don't know if the problem is about the thread with just the given code, but it is the most usual error.
First remember to set the socket timeout :
mSocket.setSoTimeout(timeout); //in milliseconds
You can however specify different timeout for connection and for all other I/O operations through the socket:
private void connectToMonitor() {
try {
socket = new Socket();
InetAddress[] iNetAddress = InetAddress.getAllByName(SERVER_ADDRESS);
SocketAddress address = new InetSocketAddress(iNetAddress[0], TCP_SERVER_PORT);
socket.setSoTimeout(10000); //timeout for all other I/O operations, 10s for example
socket.connect(address, 20000); //timeout for attempting connection, 20 s
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Second, in Android, you should perform any network I/O in separate threads!
As an example, using regular Java Threads :
String threadName = getClass().getName() + "::connect";
new Thread(new Runnable() {
#Override
public void run() {
connectToMonitor();
}
}, threadName).start();
You can set A timeout for the socket. Use Socket.setSoTimeout method
socket.setSoTimeout(timesinmilis);
by using this your socket will throw a socket timout exception. You can catch that and do what you want

Android connect to Blackberry 655+ bluetooth headset

I'm trying to write a test app which connects to BlackBerry 655+ bluetooth headset. Basically what i want to do in this app is connect to the headset and catch button pressures on it. I think that could be done by reading the socket's inputstream. Anyway, i get some errors right when i try to connect to the socket. Here's the code:
BluetoothSocket tmp = null;
try {
tmp = mDevice.createRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
} catch(IOException e) {}
mSocket = tmp;
mBtAdapter.cancelDiscovery();
try {
mSocket.connect(); // THIS ONE GIVES A "Service discovery failed" exception
} catch (IOException e1) {
Method m = null;
try {
m = mDevice.getClass().getMethod(
"createRfcommSocket", new Class[] {int.class});
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(mDevice, 1);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
mSocket = tmp;
try {
mSocket.connect(); // THIS ONE GIVES A "Connection refused" EXCEPTION
} catch (IOException e) {
e.printStackTrace();
}
}
What am i doing wrong? I already tried different ports in the m.invoke(mDevice, X) instruction but it always gives "Connection refused"
I worked with Bluetooth before but with python and Java ME so I understand the basics. I don't know much about the android API though.
Where did you get the UUID code from? That could be one of the reasons for the Service discovery failed.
Each bluetooth device may have several services each of them associated to one port (or channel). If you are running ubuntu try using the hci tools to know to which channel connect or which service to search for.
Here you have an official list with UUIDs from Bluetooth SIG. For Headset Profile the UUID is 0x1108, the UUID used by you it is Base Universally Unique Identifier and it is used for SDP.

Categories

Resources