XMPP Connection android
package com.ttg.androidxmppsample;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.net.InetAddresses;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
public class MainActivity2 extends AppCompatActivity {
String TAG = "ConnectXmpp";
String DOMAIN = "localhost";
String HOST = "10.11.227.130";
int PORT = 5222;
private String userName ="";
private String passWord = "";
public static boolean connected = false;
public static boolean isToasted = true;
public static boolean chat_created = true;
// Chat newChat;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
public AbstractXMPPConnection mConnection;
public XMPPTCPConnectionConfiguration mConnectionConfiguration;
private boolean startConnected = false;
TextView connStatus ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
Button btn = findViewById(R.id.button);
connStatus = findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
init("","");
} catch (XmppStringprepException e) {
Log.i("dbXMPP", "XmppStringprepException!");
e.printStackTrace();
}
// startLogin("lx2rvktowng3","9739876646vV");
// startLogin("","");
}
});
}
public void init(final String userName, final String passWord) throws XmppStringprepException {
Log.i("dbXMPP", "Initializing!");
//this.userName = userId;
//this.passWord = pwd;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("SomeResource");
// DomainBareJid serviceName = JidCreate.domainBareFrom(DOMAIN);
// configBuilder.setServiceName(serviceName);
// configBuilder.setXmppDomain(serviceName);
configBuilder .setXmppDomain("10.11.227.130");
// configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
configBuilder.allowEmptyOrNullUsernames();
// connection = new XMPPTCPConnection(configBuilder.build());
// connection.addConnectionListener(connectionListener);
Log.i("dbXMPP", "Initializing! 1");
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
try {
// mConnection.setReplyTimeout(10000);
connection.connect();
startConnected = true;
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, " ***** + Connected" +e.getLocalizedMessage());
}
Log.i("dbXMPP", "Initializing! 2");
}
// Connection Listener to check connection state
public class XMPPConnectionListener implements ConnectionListener {
@Override
public void connected(@NonNull final XMPPConnection connection) {
Log.i("dbXMPP", "Connected!");
connected = true;
connStatus.setText("Connected");
connStatus.setTextColor(Color.GREEN);
if (!connection.isAuthenticated()) {
// login();
}
}
@Override
public void authenticated(XMPPConnection xmppConnection, boolean b) {
Log.i("dbXMPP", "authenticated!");
connStatus.setText("Connected , authenticated");
connStatus.setTextColor(Color.GREEN);
}
@Override
public void connectionClosed() {
Log.d("dbXMPP", "ERROR connectionClosed!");
// connStatus.setText("connectionClosed");
// connStatus.setTextColor(Color.RED);
}
@Override
public void connectionClosedOnError(Exception e) {
// connStatus.setText("connectionClosedOnError");
// connStatus.setTextColor(Color.RED);
Log.d("dbXMPP", "ERROR connectionClosedOnError!");
}
private boolean loggedin = true;
public void login() {
try {
XMPPLogic.connection.login(userName, passWord);
//connection.login(userName, passWord);
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
loggedin = false;
chat_created = false;
}
if (!loggedin) {
Log.e(TAG, "Unable to login");
// disconnect();
loggedin = true;
} else {
Log.e(TAG, "Logged in");
}
}
}
/*
* startLogin creates the connection for the log in process.
* First, a connection to the server must be established. After the connection
* is established, then only can you process the login details.
* */
private void startLogin(final String username, final String password) {
/*
new Handler().postDelayed(new Runnable() {
public void run() {
// do something...
{
DomainBareJid serviceName = null;
InetAddress address = null;
try {
serviceName = JidCreate.domainBareFrom(DOMAIN);
} catch (XmppStringprepException e) {
e.printStackTrace();
}
try {
address=InetAddress.getByName(HOST);
} catch (UnknownHostException e) {
e.printStackTrace();
}
mConnectionConfiguration = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(username, password) // The username and password supplied by the user
.setHostAddress(address)// Service name
.setXmppDomain(serviceName)
.setHost(HOST) // Server host name
.setPort(5222) // Incoming port (might depend on your XMPP server software)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled) // Security mode is disabled for example purposes
.build();
mConnection = new XMPPTCPConnection(mConnectionConfiguration);
try {
mConnection.setReplyTimeout(10000);
mConnection.connect();
startConnected = true;
} catch (Exception e) {
e.printStackTrace();
}
// If the connection is successful, we begin the login process
if(startConnected) {
// connectionLogin();
Log.e(TAG, " ***** + Connected");
} else {
Log.e(TAG, "Unable to connect");
}
}
}
}, 10000);
*/
new Thread(new Runnable() {
@Override
public void run() {
DomainBareJid serviceName = null;
InetAddress address = null;
try {
serviceName = JidCreate.domainBareFrom(DOMAIN);
} catch (XmppStringprepException e) {
e.printStackTrace();
}
try {
address=InetAddress.getByName(HOST);
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
mConnectionConfiguration = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(username, password) // The username and password supplied by the user
.setResource("SomeResource")
// .setHostAddress(address)// Service name
// .setXmppDomain("jabber.org")
.setXmppDomain("jabber.org")
// .setHost(HOST) // Server host name
.setPort(5222) // Incoming port (might depend on your XMPP server software)
// .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled) // Security mode is disabled for example purposes
.allowEmptyOrNullUsernames()
.build();
} catch (XmppStringprepException e) {
e.printStackTrace();
}
mConnection = new XMPPTCPConnection(mConnectionConfiguration);
try {
// mConnection.setReplyTimeout(10000);
mConnection.connect();
startConnected = true;
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, " ***** + Connected" +e.getLocalizedMessage());
}
// If the connection is successful, we begin the login process
if(startConnected) {
// connectionLogin();
Log.e(TAG, " ***** + Connected");
runOnUiThread(new Runnable() {
@Override
public void run() {
connStatus.setText("Connected");
connStatus.setTextColor(Color.GREEN);
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
connStatus.setText("Not Connected");
connStatus.setTextColor(Color.RED);
}
});
Log.e(TAG, "Unable to connect");
}
}
}).start();
}
}
implementation "org.igniterealtime.smack:smack-tcp:4.3.0"
// Optional for XMPPTCPConnection
implementation "org.igniterealtime.smack:smack-android-extensions:4.3.0"
implementation 'org.igniterealtime.smack:smack-android:4.3.0'
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_height="wrap_content"
android:text="Connect"
tools:layout_editor_absoluteX="178dp"
tools:layout_editor_absoluteY="217dp" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_marginTop="50dp"
android:layout_height="wrap_content"
android:textSize="20dp"
android:maxLines="10"
android:text="Connection Status"
tools:layout_editor_absoluteX="166dp"
tools:layout_editor_absoluteY="381dp" />
</LinearLayout>
package com.ttg.myapplicationxmpptest;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
public class MainActivity2 extends AppCompatActivity {
protected static final String TAG = "ConnectionManager";
/*
* SERVICE_NAME and HOST_NAME are your server details.
* Make sure you edit this with your own
* */
protected static final String SERVICE_NAME = "mongoose.netaxis.co";
protected static final String HOST_NAME = "mongoose.netaxis.co";
public static AbstractXMPPConnection mConnection;
private XMPPTCPConnectionConfiguration mConnectionConfiguration;
private boolean startConnected = false;
EditText userNameET, passwordET;
TextView status;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button connnect = findViewById(R.id.button);
userNameET = findViewById(R.id.userName);
passwordET = findViewById(R.id.password);
status = findViewById(R.id.status);
connnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startLogin(userNameET.getText().toString(),passwordET.getText().toString());
// userNameET.setText("");
// passwordET.setText("");
}
});
}
/*
* startLogin creates the connection for the log in process.
* First, a connection to the server must be established. After the connection
* is established, then only can you process the login details.
* */
private void startLogin(final String username, final String password) {
new Thread(new Runnable() {
@Override
public void run() {
mConnectionConfiguration = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(username, password) // The username and password supplied by the user
.setServiceName(SERVICE_NAME) // Service name
.setHost(HOST_NAME) // Server host name
.setPort(5222) // Incoming port (might depend on your XMPP server software)
.setSecurityMode(ConnectionConfiguration.SecurityMode.ifpossible) // Security mode is disabled for example purposes
.setCompressionEnabled(true)
.setResource("sender")
.setDebuggerEnabled(true)
.build();
mConnection = new XMPPTCPConnection(mConnectionConfiguration);
try {
mConnection.connect();
startConnected = true;
} catch (Exception e) {
e.printStackTrace();
}
// If the connection is successful, we begin the login process
if(startConnected) {
Log.e(TAG, "Connected");
connectionLogin();
} else {
Log.e(TAG, "Unable to connect");
}
}
}).start();
}
private boolean loggedIn = true;
private void connectionLogin() {
try {
//XMPPConnection connection = new XMPPConnection(mConnectionConfiguration);
// xmppClient.setConnection(mConnection);
mConnection.login();
Presence presence = new Presence(Presence.Type.available);
mConnection.sendPacket(presence);
} catch (Exception e) {
loggedIn = false;
}
// If the login fails, we disconnect from the server
if(!loggedIn) {
Log.e(TAG, "Unable to login");
disconnect();
loggedIn = true;
} else {
// If the login succeeds, we implement the chat listener.
// It's important to implement the listener here so we can receive messages sent to us
// when we're offline.
// createChatListener();
// Callback to LoginScreen to change the UI to the ChatScreen listview
// EventBus.getDefault().post(new LoggedInEvent(true));
Log.e(TAG, "Logged in");
runOnUiThread(new Runnable() {
@Override
public void run() {
status.setText("Logged In : " + userNameET.getText().toString());
status.setTextColor(Color.GREEN);
}
});
}
}
private void disconnect() {
if(mConnection != null && mConnection.isConnected()) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
mConnection.disconnect();
Log.e(TAG, "Connection disconnected");
return null;
}
}.execute();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<EditText
android:id="@+id/userName"
android:layout_height="50dp"
android:textColor="#000000"
android:hint="user name"
android:layout_margin="10dp"
android:textColorHint="@color/black"
android:layout_width="match_parent"
android:text="" />
<EditText
android:id="@+id/password"
android:layout_height="50dp"
android:textColor="#000000"
android:layout_margin="10dp"
android:hint="password"
android:textColorHint="@color/black"
android:layout_width="match_parent"
android:text="" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_height="wrap_content"
android:text="Connect"
tools:layout_editor_absoluteX="178dp"
tools:layout_editor_absoluteY="217dp" />
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_marginTop="50dp"
android:layout_height="wrap_content"
android:textSize="20dp"
android:maxLines="10"
android:text="Connection Status"
tools:layout_editor_absoluteX="166dp"
tools:layout_editor_absoluteY="381dp" />
</LinearLayout>
implementation "org.igniterealtime.smack:smack-android-extensions:4.1.3"
implementation "org.igniterealtime.smack:smack-tcp:4.1.3"
package com.ttg.androidxmppsample;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.stringprep.XmppStringprepException;
import java.io.IOException;
public class MainActivityInitXMPP extends AppCompatActivity {
String TAG = "ConnectXmpp";
String DOMAIN = "jabber.org";
String HOST = "10.11.227.130";
int PORT = 5222;
private String userName ="";
private String passWord = "";
public static boolean connected = false;
XMPPConnectionListener connectionListener = new MainActivityInitXMPP.XMPPConnectionListener();
TextView connStatus ;
private boolean startConnected = false;
AbstractXMPPConnection connection = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
Button btn = findViewById(R.id.button);
connStatus = findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
init("","");
} catch (XmppStringprepException e) {
Log.i("dbXMPP", "XmppStringprepException!");
e.printStackTrace();
}
// startLogin("lx2rvktowng3","9739876646vV");
// startLogin("","");
}
});
}
public void init (String username, String password) throws XmppStringprepException {
Log.i("dbXMPP", "Initializing!");
XMPPTCPConnectionConfiguration.Builder configuration = XMPPTCPConnectionConfiguration.builder();
configuration.setUsernameAndPassword(username,password);
configuration.setSecurityMode(ConnectionConfiguration.SecurityMode.ifpossible);
configuration.setResource("SomeResource");
configuration.setXmppDomain(DOMAIN);
configuration.setPort(PORT);
configuration.allowEmptyOrNullUsernames();
connection = new XMPPTCPConnection(configuration.build());
connection.addConnectionListener(connectionListener);
try {
// mConnection.setReplyTimeout(10000);
connection.connect();
startConnected = true;
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, " ***** + Connected" +e.getLocalizedMessage());
}
}
// Connection Listener to check connection state
public class XMPPConnectionListener implements ConnectionListener {
@Override
public void connected(@NonNull final XMPPConnection connection) {
Log.i("dbXMPP", "Connected!");
connected = true;
connStatus.setText("Connected");
connStatus.setTextColor(Color.GREEN);
if (!connection.isAuthenticated()) {
// login();
}
}
@Override
public void authenticated(XMPPConnection xmppConnection, boolean b) {
Log.i("dbXMPP", "authenticated!");
connStatus.setText("Connected , authenticated");
connStatus.setTextColor(Color.GREEN);
}
@Override
public void connectionClosed() {
Log.d("dbXMPP", "ERROR connectionClosed!");
// connStatus.setText("connectionClosed");
// connStatus.setTextColor(Color.RED);
}
@Override
public void connectionClosedOnError(Exception e) {
// connStatus.setText("connectionClosedOnError");
// connStatus.setTextColor(Color.RED);
Log.d("dbXMPP", "ERROR connectionClosedOnError!");
}
}
private boolean loggedin = true;
public void login() {
try {
connection.login(userName, passWord);
//connection.login(userName, passWord);
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
loggedin = false;
// chat_created = false;
}
if (!loggedin) {
Log.e(TAG, "Unable to login");
// disconnect();
loggedin = true;
} else {
Log.e(TAG, "Logged in");
}
}
}
No comments:
Post a Comment