I own raspberry pi and android smartphone. I am trying to control raspburry pi GPIO with self-made application by android studio. The devices are able connect to each other via MQTT, but when I was trying to publish a message (on/off), it doesn't showed up in the raspberry pi terminal. There is no error detected. I have no clue, what I'm missing here. Thank you in advance for any suggestion.
public class MainActivity extends AppCompatActivity {
Switch aswitch;
MqttAndroidClient client;
TextView subText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.2.193:1883",clientId);
//client = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.43.41:1883",clientId);
}
public void Switch(View v){
aswitch = (Switch) findViewById(R.id.simpleSwitch1);
aswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true){
String topic = "rpi/gpio";
String payload = "On";
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes(StandardCharsets.UTF_8);
MqttMessage message = new MqttMessage(encodedPayload);
message.setRetained(true);
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}else{
String topic = "rpi/gpio";
String payload = "Off";
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes(StandardCharsets.UTF_8);
MqttMessage message = new MqttMessage(encodedPayload);
message.setRetained(true);
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
});
}
public void conn(View v){
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Toast.makeText(MainActivity.this,"connected",Toast.LENGTH_LONG).show();
setSubscription();
}
private void setSubscription() {
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Toast.makeText(MainActivity.this,"connection failed",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}
Related
When i used mqtt client in other activity they show me error and when i closed client in OnDestroy and then used client in different activity then it didn't give error but setactioncallback didn't work it give no success and no failure
Mainactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
login = findViewById(R.id.btn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String clientId = MqttClient.generateClientId();
client =
new MqttAndroidClient(MainActivity.this, "tcp://broker.hivemq.com:1883",
clientId);
try {
MqttConnectOptions options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.d(TAG, "onSuccess");
gotosubscribelist();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.d(TAG, "onFailure");
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
});
}
private void gotosubscribelist()
{
Intent intent = new Intent(this,SubscribelistActivity.class);
intent.putExtra("client", String.valueOf(client));
startActivity(intent);
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
client.unregisterResources();
client.close();
}
subscribe activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscribelist);
try {
MainActivity.client.connect();
} catch (MqttException e) {
e.printStackTrace();
}
channel = findViewById(R.id.channel);
subscribe = findViewById(R.id.subscribe);
mRec = (RecyclerView) findViewById(R.id.recyclerview);
newlist = new ArrayList<>();
adapter = new ChannelAdapter(this,newlist);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRec.setHasFixedSize(true);
mRec.setLayoutManager(linearLayoutManager);
mRec.setAdapter(adapter);
subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
subscribe();
}
});
}
private void subscribe()
{
Log.e("hi","1");
final String topic = channel.getText().toString();
int qos = 1;
try {
IMqttToken subToken = MainActivity.client.subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.e("suc","create");
newlist.add(topic);
}
#Override
public void onFailure(IMqttToken asyncActionToken,
Throwable exception) {
Log.e("e",exception.getMessage());
}
});
adapter.notifyDataSetChanged();
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
My problem is if i remove client.unregisterResources and client.close in onDestroy then it show
E/ActivityThread: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection#7ce0751 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection#7ce0751 that was originally bound here
and when i put client.unregisterResources and client.close in onDestroy then it didn't show error but in the subscribe function it didn't run onsuccess and onfailure, please give some suggestion
channelactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_channel);
try {
MainActivity.client.connect();
MainActivity.client.isConnected();
} catch (MqttException e) {
e.printStackTrace();
}
message = findViewById(R.id.msg);
publish = findViewById(R.id.publish);
name = getIntent().getExtras().get("currentchannelname").toString();
Rec = (RecyclerView) findViewById(R.id.recyclerview_msg);
newlist = new ArrayList<>();
adapter = new msgAdapter(this,newlist);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
Rec.setHasFixedSize(true);
Rec.setLayoutManager(linearLayoutManager);
Rec.setAdapter(adapter);
getmessage();
publish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
publishmsg();
}
});
}
private void publishmsg()
{
String topic = name;
String payload = message.getText().toString().trim();
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
MainActivity.client.publish(topic, message);
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
}
}
private void getmessage()
{
MainActivity.client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
newlist.add(message.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
Remove
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
from SubscribeActivity
In the following code of my MainActivity (which downloads a json I need in another activity and shows a loading progress bar), which starts before launching HomeActivity, I get a null object reference error (on the getProgress() method), but HomeActivity then starts anyway if I press back button.
I have searched for this kind of error, but the only solution that seems working is the one that let me starts the HomeActivity after some delay, changing setProgress method like this: (but it seems that the bar doesn't change and I don't think it's a real solution to the problem)
public void setProgress(ProgressBar bar, int progress) {
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if (bar.getProgress() == 100) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent intent = new Intent(MainActivity.this, HomePage.class);
startActivity(intent);
}
}, 4000);
}
}
----------------------------------------------------------------------
package ...
import ...
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private TextView textView;
private OkHttpClient httpClient;
private String url;
private Request request;
private static boolean loaded = false;
private FileInputStream inputStream;
private FileOutputStream outputStream;
private static final String FILE_NAME = "data.txt";
private AlertDialogConnection noResponse;
private AlertDialogConnection noInternet;
private AlertDialogConnection serverError;
private AlertDialogConnection internalError;
public MainActivity(){
this.inputStream = null;
this.outputStream = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
this.httpClient = new OkHttpClient();
this.url = "my url";
this.request = new Request.Builder().url(url).build();
this.progressBar = findViewById(R.id.progressBar);
this.progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.progressBarColor), android.graphics.PorterDuff.Mode.SRC_IN);
this.textView = findViewById(R.id.textView);
this.noResponse = new AlertDialogConnection();
this.noInternet = new AlertDialogConnection();
this.serverError = new AlertDialogConnection();
this.internalError = new AlertDialogConnection();
checkConnectionStatusAndStart();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
public void checkConnectionStatusAndStart(){
if(checkConnectionStatus())
requestData();
else{
this.noInternet.setTitle("no connection!");
this.noInternet.setText("connection error!");
this.noInternet.show(getSupportFragmentManager(), "no connection!");
}
}
public boolean checkConnectionStatus(){
boolean wifiConnection = false;
boolean mobileConnection = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null)
networkInfo = connectivityManager.getActiveNetworkInfo();
if((networkInfo != null) && networkInfo.isConnected()){
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
/* Wifi On */
wifiConnection = true;
}
if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
/* Mobile data On */
mobileConnection = true;
}
return (wifiConnection || mobileConnection);
}else{
/* You are not connected */
return false;
}
}
public void requestData(){
textView.setText("waiting server...");
httpClient.connectTimeoutMillis(); //Timeout
httpClient.writeTimeoutMillis();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
if(!call.isExecuted()){
Toast.makeText(getApplicationContext(), "server error!", Toast.LENGTH_LONG).show();
}
Log.d("HTTP-Error", "HTTP error!");
AlertDialogConnection errorDialog = new AlertDialogConnection();
errorDialog.setTitle("server error!");
errorDialog.setText("server error, try later");
errorDialog.show(getSupportFragmentManager(), "messaging error!");
}
#Override
public void onResponse(#NotNull Call call, Response response) throws IOException {
if(response.isSuccessful()){
/* HTTP-code: 200 */
final String body = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.textView)).setText("Setting of suggestion variables!");
setProgress(progressBar, 10);
try {
JSONObject json = new JSONObject(body);
try {
((TextView)findViewById(R.id.textView)).setText("retrieving server infos!");
saveJSON(json, getApplicationContext());
} catch (FileNotFoundException e) {
Log.d("File Not Found!", "FileNotFoundException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
} catch (IOException e) {
Log.d("File Not Found!", "IOException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
}
setProgress(progressBar, 90);
MainActivity.loaded = true;
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSON-Error", "parsing JSON error!");
internalError.setTitle("server error!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "JSON messaging error!");
}
}
});
}else{
/* Http-code: 500 */
Log.d("HTTP-Error", "server error!");
serverError.setTitle("server error!");
serverError.setText("server error");
serverError.show(getSupportFragmentManager(), "server error!");
}
}
});
}
public void setProgress(ProgressBar bar, int progress){
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if(bar.getProgress() == 100){
Intent intent = new Intent(this, HomePage.class);
startActivity(intent);
this.onDestroy();
}
}
private void saveJSON(JSONObject json, Context context) throws IOException {
outputStream = null;
try{
outputStream = context.openFileOutput(FILE_NAME, MODE_PRIVATE);
outputStream.write(json.toString().getBytes());
}finally {
if(outputStream != null){
outputStream.close();
}
}
}
public JSONObject loadJSON(Context context) throws IOException, JSONException {
inputStream = context.openFileInput(FILE_NAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(reader.readLine());
inputStream.close();
return jsonObject;
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
this.httpClient = null;
this.noResponse = null;
this.noInternet = null;
this.serverError = null;
this.internalError = null;
this.request = null;
this.textView = null;
this.progressBar = null;
this.url = null;
super.onDestroy();
}
#Override
protected void onResume() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onResume();
}
#Override
protected void onRestart() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onRestart();
}
#Override
protected void onPause() {
if(!loaded ){
checkConnectionStatusAndStart();
}
super.onPause();
}
}
I'm learning MQTT and Android Studio.
I want to make a simple application in Android Studio but I'm fighting from 4 days and I can`t cope with it.
Application Description:
1 Button ---> Push ---> Send to mqtt topic / message ( "mqtt" / "test" )
That`s all.
Mqtt Broker = rpi (IP: namerpibrok.ddns.net )
Broker works fine and it does not need a password or username
Problem is with Aplication - that is my first work with Android Studio.
I did everything as described on the page: https://www.hivemq.com/blog/mqtt-client-library-enyclopedia-paho-android-service
Now, when I push the button .... nothing happens.
MqttAndroidClient client;
private static final String TAG = "LOG";
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
private Object bytes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(this.getApplicationContext(), "rpidomwroled.ddns.net:1883", clientId);
MqttConnectOptions options = new MqttConnectOptions();
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this,"Połączono", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this,"Połączono", Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
MqttAndroidClient client;
private static final String TAG = "LOG";
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
private Object bytes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(this.getApplicationContext(), "rpidomwroled.ddns.net:1883", clientId);
MqttConnectOptions options = new MqttConnectOptions();
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this,"Połączono", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this,"Połączono", Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
public void pub(View v)
{
String topic = "mqtt";
String payload = "mqtt";
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
client.publish(topic, message);
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
}
}
}
Can anybody tell me what I'm doing wrong?
This code is worked for me
String topic = "mqtt";
MqttMessage message = new MqttMessage();
message.setPayload("Message from IoT dev".getBytes());
client.publish(topic, message);
you can get call backs in
client.setCallback(new IoTCallbacks() {
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
I'm creating an app in Android using Socket.IO. I am stuck at the Login itself. Here is my code for Login
public class MainActivity extends AppCompatActivity {
EditText uname_et, pwd_et;
Button log;
String username, password;
private Socket mSocket;
private Emitter.Listener onLogin = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(args[0].toString(), "data");
Log.w("yes ", "in evtLogin");
// JSONObject data = (JSONObject) args[0];
}
};
{
try {
String URL = "http://MYIP:8081";
mSocket = IO.socket(URL);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname_et = (EditText) findViewById(R.id.username_input);
pwd_et = (EditText) findViewById(R.id.pwd);
log = (Button) findViewById(R.id.sign_in_button);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signin();
}
});
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i("Make Emit", "Emit");
Log.w(mSocket.connected() + " - ", "Connection status");
}
});
mSocket.on("evtLogin", onLogin);
mSocket.connect();
}
private void signin() {
username = uname_et.getText().toString();
password = pwd_et.getText().toString();
mSocket.emit("userName", username);
mSocket.emit("Password", password);
}
#Override
protected void onDestroy() {
super.onDestroy();
mSocket.off("evtLogin", onLogin);
}
}
I'm not sure that socket is even connected or not, I'm gettong logs from Socket.EVENT_CONNECT
08-31 12:22:22.062 13399-13441/com.fis.kotsocket I/Make Emit﹕ Emit
08-31 12:22:22.063 13399-13441/com.fis.kotsocket W/true -﹕ Connection status
But onLogin listener is not called.
As a newbie I am not sure what to do exactly.
js code
//code for login event
socket.on('evtLogin', function (loginData) {
console.log('loged');
User.findOne({'login.userName':loginData.userName,'login.password':loginData.password},function(err,user){
if(err){throw err;}
else {if(!user){
console.log('not a authenticated user');
}
else
{
var userType;
User.find({'login.userName':loginData.userName,'login.password':loginData.password},function(err,rslt){
if(err){throw err;}
else
{
userType = JSON.stringify(rslt[0]['userType'].userId);
socket.emit('evtUserType',userType);
}
})
}
}
});
console.log('done');
});
Your socket is not getting initialized.
Try this initialization:
private Socket mSocket;
{
try {
mSocket = IO.socket("enter url here");
} catch (URISyntaxException e) {}
}
Or it might be that you are not emitting the evtLogin event from your javascript code.
I am trying to create an XMPP client using the latest version of Smack 4.1.0-beta. But i am running into an error when trying login into a local running OpenFire server.
org.jivesoftware.smack.SmackException: SASL Authentication failed. No known authentication mechanisims.
I tried all kind of combinations of user credentials but so far no luck. When trying to connect to the server with Pidgin or Adium al is ok. Any clue what i am missing in the code?
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("admin", "admin")
.setServiceName("localhost")
.setHost("localhost")
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setPort(5222)
.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect();
connection.login();
connection.disconnect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
Here is the complete solution please look at this carefully...
public class NewClientActivity extends Activity {
EditText etUsername, etPassword;
Button bSubmit;
AbstractXMPPConnection mConnection;
ConnectionListener connectionListener = new ConnectionListener() {
#Override
public void connected(XMPPConnection xmppConnection) {
Log.d("xmpp", "connected");
try {
SASLAuthentication.registerSASLMechanism(new SASLMechanism() {
#Override
protected void authenticateInternal(CallbackHandler callbackHandler) throws SmackException {
}
#Override
protected byte[] getAuthenticationText() throws SmackException {
byte[] authcid = toBytes('\u0000' + this.authenticationId);
byte[] passw = toBytes('\u0000' + this.password);
return ByteUtils.concact(authcid, passw);
}
#Override
public String getName() {
return "PLAIN";
}
#Override
public int getPriority() {
return 410;
}
#Override
public void checkIfSuccessfulOrThrow() throws SmackException {
}
#Override
protected SASLMechanism newInstance() {
return this;
}
});
mConnection.login();
} catch (XMPPException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this, "Incorrect username or password", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void authenticated(XMPPConnection xmppConnection, boolean b) {
Log.d("xmpp", "authenticated");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this,"Logged in successfully...",Toast.LENGTH_LONG ).show();
}
});
}
#Override
public void connectionClosed() {
Log.d("xmpp", "connection closed");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("xmpp", "cononection closed on error");
}
#Override
public void reconnectionSuccessful() {
Log.d("xmpp", "reconnection successful");
}
#Override
public void reconnectingIn(int i) {
Log.d("xmpp", "reconnecting in " + i);
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("xmpp", "reconnection failed");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_client);
findViews();
}
private void findViews() {
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bSubmit = (Button) findViewById(R.id.bSubmit);
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] params = new String[]{etUsername.getText().toString(), etPassword.getText().toString()};
new Connect().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
}
});
}
class Connect extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
XMPPTCPConnectionConfiguration config = null;
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setServiceName("192.168.1.60").setHost("192.168.1.60")
.setDebuggerEnabled(true)
.setPort(5222)
.setUsernameAndPassword(params[0], params[1])
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setCompressionEnabled(false);
config = builder.build();
mConnection = new XMPPTCPConnection(config);
try {
mConnection.setPacketReplyTimeout(10000);
mConnection.addConnectionListener(connectionListener);
mConnection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
}
}
Update :- For smack 4.2.0-beta2 version use below code to configure XmppConnection for PLAIN authentication.
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setHost("example.com");
builder.setPort(5222);
/*builder.setServiceName("example.com");*/ //for older version < 4.2.0-beta2
try
{
builder.setXmppDomain(JidCreate.domainBareFrom("example.com"));
}
catch (XmppStringprepException e)
{
e.printStackTrace();
}
/*builder.setServiceName("example.com");*/
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
builder.setCompressionEnabled(true);
builder.setConnectTimeout(30000);
/*builder.setSendPresence(false);*/
try
{
TLSUtils.acceptAllCertificates(builder);
}
catch (NoSuchAlgorithmException|KeyManagementException e)
{
e.printStackTrace();
}
TLSUtils.disableHostnameVerificationForTlsCertificates(builder);
final Map<String, String> registeredSASLMechanisms = SASLAuthentication.getRegisterdSASLMechanisms();
for(String mechanism:registeredSASLMechanisms.values())
{
SASLAuthentication.blacklistSASLMechanism(mechanism);
}
SASLAuthentication.unBlacklistSASLMechanism(SASLPlainMechanism.NAME);
xmppConnection=new XMPPTCPConnection(builder.build());
I wrongly imported the wrong dependencies. When checking out the documentation (https://github.com/igniterealtime/Smack/wiki/Smack-4.1-Readme-and-Upgrade-Guide) importing the correct dependencies using Gradle solved the issue.
compile("org.igniterealtime.smack:smack-java7:4.1.0-beta1")
compile("org.igniterealtime.smack:smack-tcp:4.1.0-beta1")
compile("org.igniterealtime.smack:smack-extensions:4.1.0-beta1")
try using ip address for host / servicename