XMPP Connection with Smack 4.1 on Android Studio
Asked Answered
P

3

10

I am trying to do an XMPP Connection with Smack 4.1.0 rc1 from https://github.com/igniterealtime/Smack

I followed this guide: https://github.com/igniterealtime/Smack/wiki/Smack-4.1-Readme-and-Upgrade-Guide importing the Gradle.

Source code:

package com.example.xmpp_app;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;

import java.io.IOException;

public class MainActivity extends ActionBarActivity {

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

        // Create the configuration for this new connection
        XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
        configBuilder.setUsernameAndPassword("[email protected]", "password123");
        configBuilder.setResource("test");
        configBuilder.setServiceName("example.com");

        AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
        // Connect to the server
        try {
            connection.connect();
        } catch (SmackException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XMPPException e) {
            e.printStackTrace();
        }
        // Log into the server
        try {
            connection.login();
        } catch (XMPPException e) {
            e.printStackTrace();
        } catch (SmackException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Disconnect from the server
        connection.disconnect();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://oss.sonatype.org/content/repositories/snapshots'
        }
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

build gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.xmpp_app"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile "org.igniterealtime.smack:smack-java7:4.1.0-rc1"
    // Optional for XMPPTCPConnection
    compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
    // Optional for XMPP-IM (RFC 6121) support (Roster, Threaded Chats, …)
    compile "org.igniterealtime.smack:smack-im:4.1.0-rc1"
    // Optional for XMPP extensions support
    compile "org.igniterealtime.smack:smack-extensions:4.1.0-rc1"
}

ERROR:

03-20 20:34:33.830    1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
03-20 20:34:33.830    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 11345: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
03-20 20:34:33.850    1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
03-20 20:34:33.850    1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
03-20 20:34:33.850    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 11351: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
03-20 20:34:33.850    1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
03-20 20:34:33.920    1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
03-20 20:34:33.920    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 9039: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
03-20 20:34:33.950    1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
03-20 20:34:34.100    1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
03-20 20:34:34.110    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 364: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
03-20 20:34:34.110    1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
03-20 20:34:34.150    1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
03-20 20:34:34.150    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 386: Landroid/content/res/TypedArray;.getType (I)I
03-20 20:34:34.150    1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
03-20 20:34:35.790    1005-1005/com.example.xmpp_app D/dalvikvm﹕ GC_FOR_ALLOC freed 221K, 9% free 3164K/3452K, paused 105ms, total 115ms
03-20 20:34:38.420    1005-1005/com.example.xmpp_app D/dalvikvm﹕ GC_FOR_ALLOC freed 295K, 10% free 3382K/3744K, paused 90ms, total 93ms
03-20 20:34:40.250    1005-1005/com.example.xmpp_app D/dalvikvm﹕ GC_FOR_ALLOC freed 349K, 11% free 3531K/3952K, paused 80ms, total 85ms
03-20 20:34:40.310    1005-1005/com.example.xmpp_app E/dalvikvm﹕ Could not find class 'javax.naming.directory.InitialDirContext', referenced from method org.jivesoftware.smack.util.dns.javax.JavaxResolver.<clinit>
03-20 20:34:40.310    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve new-instance 1688 (Ljavax/naming/directory/InitialDirContext;) in Lorg/jivesoftware/smack/util/dns/javax/JavaxResolver;
03-20 20:34:40.320    1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x22 at 0x000c
03-20 20:34:40.360    1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method javax.naming.directory.DirContext.getAttributes, referenced from method org.jivesoftware.smack.util.dns.javax.JavaxResolver.lookupSRVRecords
03-20 20:34:40.360    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve interface method 12701: Ljavax/naming/directory/DirContext;.getAttributes (Ljava/lang/String;[Ljava/lang/String;)Ljavax/naming/directory/Attributes;
03-20 20:34:40.370    1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0011
03-20 20:34:40.370    1005-1005/com.example.xmpp_app D/dalvikvm﹕ DexOpt: unable to opt direct call 0x319e at 0x0e in Lorg/jivesoftware/smack/util/dns/javax/JavaxResolver;.<clinit>
03-20 20:34:40.410    1005-1005/com.example.xmpp_app W/dalvikvm﹕ Exception Ljava/lang/NoClassDefFoundError; thrown while initializing Lorg/jivesoftware/smack/util/dns/javax/JavaxResolver;
03-20 20:34:41.330    1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method javax.security.sasl.Sasl.createSaslClient, referenced from method org.jivesoftware.smack.sasl.javax.SASLJavaXMechanism.authenticateInternal
03-20 20:34:41.330    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve static method 12731: Ljavax/security/sasl/Sasl;.createSaslClient ([Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Ljavax/security/auth/callback/CallbackHandler;)Ljavax/security/sasl/SaslClient;
03-20 20:34:41.340    1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x77 at 0x001a
03-20 20:34:41.340    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve exception class 1708 (Ljavax/security/sasl/SaslException;)
03-20 20:34:41.350    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to find exception handler at addr 0x21
03-20 20:34:41.350    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY:  rejected Lorg/jivesoftware/smack/sasl/javax/SASLJavaXMechanism;.authenticateInternal ()V
03-20 20:34:41.350    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY:  rejecting opcode 0x0d at 0x0021
03-20 20:34:41.350    1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY:  rejected Lorg/jivesoftware/smack/sasl/javax/SASLJavaXMechanism;.authenticateInternal ()V
03-20 20:34:41.350    1005-1005/com.example.xmpp_app W/dalvikvm﹕ Verifier rejected class Lorg/jivesoftware/smack/sasl/javax/SASLJavaXMechanism;
03-20 20:34:41.370    1005-1005/com.example.xmpp_app W/dalvikvm﹕ Exception Ljava/lang/VerifyError; thrown while initializing Lorg/jivesoftware/smack/SmackInitialization;
03-20 20:34:41.370    1005-1005/com.example.xmpp_app W/dalvikvm﹕ Exception Ljava/lang/VerifyError; thrown while initializing Lorg/jivesoftware/smack/ConnectionConfiguration;
03-20 20:34:41.380    1005-1005/com.example.xmpp_app D/AndroidRuntime﹕ Shutting down VM
03-20 20:34:41.380    1005-1005/com.example.xmpp_app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a3bba8)
03-20 20:34:41.540    1005-1005/com.example.xmpp_app D/dalvikvm﹕ GC_FOR_ALLOC freed 438K, 14% free 3576K/4112K, paused 59ms, total 64ms
03-20 20:34:41.580    1005-1005/com.example.xmpp_app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.xmpp_app, PID: 1005
    java.lang.VerifyError: org/jivesoftware/smack/sasl/javax/SASLJavaXMechanism
            at org.jivesoftware.smack.sasl.javax.SASLJavaXSmackInitializer.initialize(SASLJavaXSmackInitializer.java:28)
            at org.jivesoftware.smack.SmackInitialization.loadSmackClass(SmackInitialization.java:232)
            at org.jivesoftware.smack.SmackInitialization.parseClassesToLoad(SmackInitialization.java:193)
            at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:163)
            at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:148)
            at org.jivesoftware.smack.SmackInitialization.<clinit>(SmackInitialization.java:116)
            at org.jivesoftware.smack.SmackConfiguration.getVersion(SmackConfiguration.java:96)
            at org.jivesoftware.smack.ConnectionConfiguration.<clinit>(ConnectionConfiguration.java:38)
            at com.example.xmpp_app.MainActivity.onCreate(MainActivity.java:29)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-20 20:39:44.485    1005-1005/com.example.xmpp_app I/Process﹕ Sending signal. PID: 1005 SIG: 9

Could someone help me with this problem, please? I am just trying to check if the connection works..

Puncture answered 21/3, 2015 at 1:11 Comment(1)
android.os.NetworkOnMainThreadException see [this page][1]. [1]: #8706964Emeliaemelin
S
15

Replace smack-java7 with smack-android in your build.gradle. This is documented in Smack's README.

Smaragdine answered 21/3, 2015 at 7:31 Comment(4)
Thanks it seems that it worked but i have another issue could you please help me on this? it says now... : 03-21 14:57:30.332 1176-1176/com.securechat.my_xmpp_app W/System.err﹕ org.jivesoftware.smack.SmackException$ConnectionException: The following addresses failed: 'xx.xx.xx.xx:5222' failed because java.net.SocketException: socket failed: EACCES (Permission denied) 03-21 14:57:30.372 1176-1176/com.securechat.my_xmpp_app W/System.err﹕ at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectUsingConfiguration(XMPPTCPConnection.java:574) My ports are already forwardedPuncture
Looks you don't have requested the internet permission.Smaragdine
I found some guides how to request internet permission but i can not test it coz im not at home now, how can i try it with my localhost? when i try this it says Exception while resovling SRV records for 127.0.0.1. Consider adding '_xmpp-(server|client)._tcp' DNS SRV Records android.os.NetworkOnMainThreadExceptionPuncture
Hello, I am facing same error, i can't find it..can you please help me.!!Nigercongo
V
1

This is an upgrade of my last FCM XMPP Connection Server application. Now, this project uses the latest version at this time of the Smack library (4.1.8). I think that the library for android is pretty the same for the java server.

https://github.com/carlosCharz/fcmxmppserverv2

This is my sample java project to showcase the Firebase Cloud Messaging (FCM) XMPP Connection Server. This server sends data to a client app via the FCM CCS Server using the XMPP protocol.

https://github.com/carlosCharz/fcmxmppserver

And also I've created a video in youtube where I explain what the changes are.

https://www.youtube.com/watch?v=KVKEj6PeLTc

Hope you find it useful.

Here is a code snippet for the implementation:

    public class CcsClient implements StanzaListener {

    //Other code

    public void connect() throws XMPPException, SmackException, IOException {
    XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
    XMPPTCPConnection.setUseStreamManagementDefault(true);

    XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
    config.setServiceName("FCM XMPP Client Connection Server");
    config.setHost(Util.FCM_SERVER);
    config.setPort(Util.FCM_PORT);
    config.setSecurityMode(SecurityMode.ifpossible);
    config.setSendPresence(false);
    config.setSocketFactory(SSLSocketFactory.getDefault());
    // Launch a window with info about packets sent and received
    config.setDebuggerEnabled(mDebuggable);

    // Create the connection
    connection = new XMPPTCPConnection(config.build());

    // Connect
    connection.connect();

    // Enable automatic reconnection
    ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection();

    // Handle reconnection and connection errors
    connection.addConnectionListener(new ConnectionListener() {

        @Override
        public void reconnectionSuccessful() {
            logger.log(Level.INFO, "Reconnection successful ...");
            // TODO: handle the reconnecting successful
        }

        @Override
        public void reconnectionFailed(Exception e) {
            logger.log(Level.INFO, "Reconnection failed: ", 
        e.getMessage());
            // TODO: handle the reconnection failed
        }

        @Override
        public void reconnectingIn(int seconds) {
            logger.log(Level.INFO, "Reconnecting in %d secs", seconds);
            // TODO: handle the reconnecting in
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            logger.log(Level.INFO, "Connection closed on error");
            // TODO: handle the connection closed on error
        }

        @Override
        public void connectionClosed() {
            logger.log(Level.INFO, "Connection closed");
            // TODO: handle the connection closed
        }

        @Override
        public void authenticated(XMPPConnection arg0, boolean arg1) {
            logger.log(Level.INFO, "User authenticated");
            // TODO: handle the authentication
        }

        @Override
        public void connected(XMPPConnection arg0) {
            logger.log(Level.INFO, "Connection established");
            // TODO: handle the connection
        }
    });

    // Handle incoming packets (the class implements the StanzaListener)
    connection.addAsyncStanzaListener(this,
            stanza -> stanza.hasExtension(Util.FCM_ELEMENT_NAME, Util.FCM_NAMESPACE));

    // Log all outgoing packets
    connection.addPacketInterceptor(stanza -> logger.log(Level.INFO, 
    "Sent: {}", stanza.toXML()), stanza -> true);

    connection.login(fcmServerUsername, mApiKey);
    logger.log(Level.INFO, "Logged in: " + fcmServerUsername);
    }
  }
Vanover answered 24/10, 2016 at 17:23 Comment(2)
Hi. is this known issue for you ? connectionClosedOnError -> Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object referenceTryparsamide
Hi. No. It never happened to me. Did you get a compilation error? Runtime error?Vanover
S
0

Try to connect server with XMPPConnection class.

How to connect:

XMPPConnection con = new XMPPTCPConnection("igniterealtime.org");
con.connect();
Sholokhov answered 21/3, 2015 at 5:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.