Wednesday, November 20, 2024

CoroutineScope : Android

    CoroutineScope : Android

  • Lifescycle scope
  • Global Scope
  • ViewmodelScope (Custom Scope )

Lifescycle scope

Use lifecycle-aware scopes like lifecycleScope or viewLifecycleOwner.lifecycleScope provided by Jetpack's Lifecycle library to automatically manage coroutine lifecycles.


Global Scope

Global scope alive till application running

Viewmodel Scope


Viewmodel scope will alive till activity or fragment

can able to use multiple fragment or activity.




Tuesday, November 12, 2024

What are Scope functions in kotlin?

 Below example for list scope function in kotlin 


  • let
  • run
  • with
  • apply
  • also

let

 The basic functionality of all the scope functions is the same i.e. to execute a block of code on an object.




Saturday, April 29, 2023

Android - The Crashlytics build ID is missing.

 Android - The Crashlytics build ID is missing. 


When i integrate  Firebase Crashlytics  getting following error .


The Crashlytics build ID is missing



kindly add following lines in  string.xml


<string name="com.crashlytics.android.build_id">1</string>

Tuesday, March 21, 2023

Android : Could not find com.twitter.sdk.android:twitter-core:3.1.1

While integrate Twitter signup integration in android . I'm getting following error 


Execution failed for task ':app:mergeDebugNativeLibs'.

> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.

   > Could not find com.twitter.sdk.android:twitter-core:3.1.1.

     Searched in the following locations:

       - https://dl.google.com/dl/android/maven2/com/twitter/sdk/android/twitter-core/3.1.1/twitter-core-3.1.1.pom

       - https://repo.maven.apache.org/maven2/com/twitter/sdk/android/twitter-core/3.1.1/twitter-core-3.1.1.pom

     Required by:

         project : app


Error



Solution 


Add following line in setting.gradle file 

pluginManagement {
repositories {
maven {
url ("https://github.com/jitsi/jitsi-maven-repository/raw/master/releases")
}
maven{
url("https://jcenter.bintray.com")
}

maven { url 'https://jitpack.io' }

gradlePluginPortal()
google()
mavenCentral()

}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {

maven {
url ("https://github.com/jitsi/jitsi-maven-repository/raw/master/releases")
}
google()
mavenCentral()

maven{
url("https://jcenter.bintray.com")
}

maven { url 'https://jitpack.io' }
}
}












Saturday, December 3, 2022

Android : Jitsi starts dialing up call out a phone number with room id some android devices

 Android  : Jitsi starts dialing up call out a phone number with room id some android devices

Solution 

Make call-integration.enabled  false


 options

                    = new JitsiMeetConferenceOptions.Builder()

                    .setRoom(roomID)

                    .setServerURL(domainURl)

                    .setConfigOverride("requireDisplayName", true)

                    .setFeatureFlag("call-integration.enabled", false)


Tuesday, November 29, 2022

Data Binding is not working after we change the package name...? Android Studio

  Data Binding is not working after we change the package name...?Android Studio


Solution:


1. Build > Clean Project


2.Go to your Build.gradle (Module) and disable databinding:


android {

    buildFeatures {

        viewBinding false

    }

}


3.File > Sync Project with Gradle Files


4.Build > Rebuild Project ,Now enable databinding again:


android {

   buildFeatures {

        viewBinding true

    }

}


5.File > Sync Project with Gradle Files

Wednesday, November 23, 2022

When enable setPersistenceEnabled(true). Firebase Realtime Database retrieving old data ?

 When enable setPersistenceEnabled(true). Firebase Realtime Database retrieving old  data ?

its showing old data. for that u have to add one more line.

FirebaseDatabase.getInstance().setPersistenceEnabled(true);
FirebaseDatabase.getInstance().getReference().keepSynced(true);

Tuesday, August 2, 2022

How to Update UserOnline Status Android Smack ?

 How to Update UserOnline Status  Android Smack ?


Presence p = new Presence(Presence.Type.available, "" +mode, 42, Presence.Mode.away);
ConnectionManager.mConnection.sendStanza(p);

Tuesday, July 19, 2022

Duplicate class org.xmlpull.mxp1.MXParser found in modules xpp3-1.1.4c (xpp3:xpp3:1.1.4c) and xpp3_min-1.1.4c (xpp3:xpp3_min:1.1.4c)

 

Duplicate class org.xmlpull.mxp1.MXParser found in modules xpp3-1.1.4c (xpp3:xpp3:1.1.4c) and xpp3_min-1.1.4c (xpp3:xpp3_min:1.1.4c)

Duplicate class org.xmlpull.v1.XmlPullParser found in modules xpp3-1.1.4c (xpp3:xpp3:1.1.4c) and xpp3_min-1.1.4c (xpp3:xpp3_min:1.1.4c)

Duplicate class org.xmlpull.v1.XmlPullParserException found in modules xpp3-1.1.4c (xpp3:xpp3:1.1.4c) and xpp3_min-1.1.4c (xpp3:xpp3_min:1.1.4c)



Solution

Add gradle 

                                      (here Your Project)

implementation ("org.igniterealtime.smack:smack-tcp:4.4.0")
/* {
exclude group: "xmlpull", module: "xmlpull"
exclude module: 'xpp3'
}


Tuesday, July 12, 2022

Android Smack Unfriend Request

 Android Smack Unfriend Request 


public static void  sendFriendshipRequest(EntityBareJid toJid , String name, String stanzaID) throws SmackException.NotConnectedException, InterruptedException {
Presence presence = new Presence(Presence.Type.unsubscribe);
presence.setTo(toJid);
presence.setFrom(fromJid);

presence.setStanzaId(stanzaID);
mConnection.sendStanza(presence);
mConnection.addStanzaSendingListener(new StanzaListener() {
@Override
public void processStanza(Stanza packet) {
Presence presence = (Presence) packet;
Presence.Mode mode = presence.getMode();
// Toast.makeText(act, "Un friend succefully " +name, Toast.LENGTH_SHORT).show();

if (mode == null) return;
switch (mode) {
case available:
case chat:
// We assume that only a switch to available and chat indicates user activity
// since other mode changes could be also a result of some sort of automatism

break;
default:
break;
}
}
}, StanzaTypeFilter.PRESENCE);
}

Saturday, July 9, 2022

Android SMACK get USER Online Status (Presence)

 Android SMACK get USER  Online Status 


public void getUserStatus(){
{
Presence presence;
presence = roster.getPresence(jid);
if (presence.getMode().name().equalsIgnoreCase("available")) {

} else if (presence.getMode().name().equalsIgnoreCase("away")) {


} else if(presence.getMode().name().equalsIgnoreCase("xa")){

}
else if(presence.getMode().name().equalsIgnoreCase("chat")){

}
else {
//dnd
}
}

Friday, July 1, 2022

XMPP SMACK Connection android Test

 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");
}

}
}

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...