I am implementing socket messaging app using nodejs server ,html and android client. So that, i have implemented the following ways,
Step 1: Create the server with the following code which works fine.
const express = require('express');
const app = express();
const server = app.listen(3000,console.log("Socket.io Hello Wolrd server started!"));
const io = require('socket.io')(server);
io.on('connection', (socket) => {
//console.log("Client connected!");
socket.on('chat_sample_test', (msg) => {
console.log(msg.id);
console.log(msg.message);
socket.emit(msg.id, msg.message);
})
});
Step 2: I have created HTML client app with the following code and it is connected with server and works perfectly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var socket = io("http://192.168.1.138:3000");
socket.on("computer", function(msg) {
document.getElementById('server').innerHTML = msg;
});
$(document).ready(function(){
$("#btnSend").click(function(){
sendMsg();
});
$('#inptBox1').keypress(function (e) {
if (e.which == 13) {
sendMsg();
return false; //<---- Add this line
}
});
});
function sendMsg(){
var message=$("#inptBox1").val();
var messageObj={};
messageObj.id="mobile";
messageObj.message=message;
socket.emit('chat_sample_test', messageObj);
}
</script>
<p id="server" ></p>
<p id="client"></p>
<input type="text" id="inptBox1" placeholder="Enter msg">
<button id="btnSend">Send</button>
</body>
</html>
Step 3: I have implemented Android client with the following code and it's also connected with server works fine.
Custom Application class:
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.reconnection = false;
mSocket = IO.socket("http://192.168.1.138:3000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
MainActivity Class:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import io.socket.client.Ack;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText messageBox;
Button sendButton;
ListView chatroom;
ChatAdapter chatAdapter;
List<ChatModel> listItems = new ArrayList<>();
private Socket mSocket;
boolean isConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChatApplication app = (ChatApplication) getApplication();
mSocket = app.getSocket();
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("mobile",onMessageReceive);
mSocket.connect();
init();
}
void init() {
chatroom = (ListView) findViewById(R.id.chatroom);
sendButton = (Button) findViewById(R.id.sendButton);
messageBox = (EditText) findViewById(R.id.messageBox);
sendButton.setOnClickListener(this);
}
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isConnected) {
Toast.makeText(getApplicationContext(),
"Connected", Toast.LENGTH_LONG).show();
isConnected = true;
}
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
isConnected = false;
Toast.makeText(getApplicationContext(),
"Disconnected", Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Connection Error", Toast.LENGTH_LONG).show();
mSocket.connect();
}
});
}
};
Emitter.Listener onMessageReceive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (args.length > 0) {
JSONObject data = (JSONObject) args[0];
String username="";
String message="";
try {
username = data.getString("username");
message = data.getString("message");
Log.e("RECEIVE",username.concat(" "+message));
setAdapter(username, message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
};
void setAdapter(String name, String message) {
ChatModel chatModel = new ChatModel();
chatModel.setUserName(name);
chatModel.setMessage(message);
listItems.add(chatModel);
if (chatAdapter == null) {
chatAdapter = new ChatAdapter(this, listItems);
chatroom.setAdapter(chatAdapter);
} else {
chatAdapter.notifyDataSetChanged();
}
chatroom.setSelection(chatAdapter.getCount() - 1);
}
private void attemptSend() {
String message = messageBox.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
return;
}
messageBox.setText("");
try {
JSONObject obj = new JSONObject();
obj.put("username", "Hassan");
obj.put("message", message);
obj.put("id", "computer");
mSocket.emit("chat_sample_test", obj, new Ack() {
#Override
public void call(Object... args) {
Toast.makeText(MainActivity.this,"Message received by device",Toast.LENGTH_SHORT).show();
}
});
setAdapter("me", message);
Log.e("SEND",message);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sendButton:
attemptSend();
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off(Socket.EVENT_CONNECT, onConnect);
mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("mobile", onMessageReceive);
}
}
My logic here is, from the html application, i will send the message to mobile and vice versa.First, I have connected with the chat_sample_test room. when i tried to send the message using html application, the server prints the message based on the console i have added in nodejs server. but the mobile not receiving the message. the same happening in mobile end.No error found.
NOTE:
when i try to send the message to mobile , i have added the id as mobile (mobile need to receive the message), where as in mobile i have added id as computer(Computer need to receive the message)
Helps will be appreciated.
Just now i found the answer. thank you guys who are all try to solve the issue.
const express = require('express');
const app = express();
const server = app.listen(3000,console.log("Socket.io Hello Wolrd server started!"));
const io = require('socket.io')(server);
io.on('connection', (socket) => {
//console.log("Client connected!");
socket.on('chat_sample_test', (msg) => {
console.log(msg.id);
console.log(msg.message);
socket.broadcast.emit(msg.id, msg.message);//here added broadcast obj.So now working fine.
})
});
Related
I was creating a application using socket.io in native android application to communicate with websockets Tester. I have tested it using a online WebSocketServer , but each time when trying to check the connection in android device, 'Connection Error` is Logged.
Error : io.socket.engineio.client.EngineIOException: websocket error
java.net.ProtocolException: Expected HTTP 101 response but was '404 Not Found'
onlineTestingPortal link :https://www.piesocket.com/websocket-tester
SocketServerCode:
package com.example.appsocket;
import android.util.Log;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import io.socket.engineio.client.transports.WebSocket;
public class SocketServer {
private Socket mSocket;
private static SocketServer lbInstance = new SocketServer();
public static SocketServer getInstance() {
return lbInstance;
}
public void callSocketServer(){
try {
IO.Options options = new IO.Options();
options.transports = new String[]{ WebSocket.NAME};
mSocket = IO.socket("wss://demo.piesocket.com/v3/channel_123?api_key=VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV¬ify_self",options);
mSocket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
System.out.println("Connection Error");
}
});
mSocket.connect();
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
System.out.println("SocketServer: connected call back" + args[0].toString());
mSocket.emit("YOUR_TOPIC", "YOUR_DATA_VALUE");
}
});
} catch (URISyntaxException e) {
System.out.println("Exception is : " + e);
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SocketServer.getInstance().callSocketServer();
}
}
Your problem is because of using socket.io library, you don't need socket.io.
In this link, the correct way to connect to ws protocol is mentioned
I am trying to use socket.io to connect to the Nodejs server and Android client. I am getting the xhr poll error when trying to connect. I have seen such issues raised by other people, but with no solution. I have socket io 2.1.1 on node server and using 'io.socket:socket.io-client:0.8.3' in Android. My Android version is Oreo.
This is my Android client code:
package com.example.socketiodemo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import io.socket.client.IO;
import io.socket.client.Manager;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends AppCompatActivity {
private TextView display_text;
private Socket mSocket;
Manager mManager;
private boolean fClientClosedConnection;
private boolean fClientIsConnected;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
display_text = (TextView)findViewById(R.id.display_text);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
fClientClosedConnection = false;
fClientIsConnected = false;
new MyAsyncTask(mSocket).execute();
}
#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);
}
private class MyAsyncTask extends AsyncTask<String, Void, String> {
Socket mSocket;
Manager mManager;
MyAsyncTask(Socket socket) {
mSocket = socket;
}
#Override
protected String doInBackground(String... params) {
Log.e(TAG, "Initiating the connection");
try {
mSocket = IO.socket("http://192.168.0.104:4444");
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onTimeoutError);
mSocket.on(Socket.EVENT_ERROR, onError);
mSocket.on("data", onNewMessage);
mSocket.connect();
while (!fClientClosedConnection) {
// Keep the thread active
}
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
Log.e(TAG, "Finished the background Process");
return "";
}
#Override
protected void onPostExecute(String result) {
mSocket.close();
}
}
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "onConnect");
if(!fClientIsConnected) {
Toast.makeText(getApplicationContext(),
"Client is connected", Toast.LENGTH_LONG).show();
fClientIsConnected = true;
}
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "diconnected");
fClientIsConnected = false;
Toast.makeText(getApplicationContext(),
"Client is disconnected", Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Error connecting: " + args[0].toString());
Toast.makeText(getApplicationContext(),
"Client connect error", Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onTimeoutError = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Timeout Error ");
}
});
}
};
private Emitter.Listener onError = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Error ");
}
});
}
};
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String message;
try {
message = data.getString("message");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
printMessage(message);
if (message.contentEquals("Bye"))
{
fClientClosedConnection = true;
}
}
});
}
};
private void printMessage (String message)
{
display_text.setText(message);
}
}
This is my nodejs server:
process.title = 'node-android';
var app = require('http').createServer()
var io = require('socket.io')(app);
app.listen(4444, onListenStart);
io.on('connection', onConnect);
function onListenStart()
{
console.log("Server listening on port: " + SERVER_PORT);
}
function onConnect(client)
{
console.log("client is connected");
client.emit("data", { message: 'Hello'});
client.on('event', onMessageReceived);
client.on('disconnect', onDisconnect);
}
function onMessageReceived(data)
{
console.log(data);
}
function onDisconnect()
{
console.log("client is disconnected");
}
I get these logs:
05-20 21:48:56.404 28026-28026/com.example.socketiodemo E/MainActivity: Error connecting: io.socket.engineio.client.EngineIOException: xhr poll error
05-20 21:48:57.921 28026-28026/com.example.socketiodemo E/MainActivity: Error connecting: io.socket.engineio.client.EngineIOException: xhr poll error
Please help, as I have been stuck on this since 3 days.
I have socket io 2.1.1 on node server and using 'io.socket:socket.io-client:0.8.3'
I had similar situation, changing library version to 1.0.0 helped.
you must add this code in application tag in manifest like below,
It solved Error connecting: io.socket.engineio.client.EngineIOException: xhr poll error
same issues
<Application . . android:usesCleartextTraffic="true"> . . . <Application/>
I am trying out the WebSockets with Fallbacks transports for Android, Node.js and Atmosphere example. I get an the following error:
/home/mofa/NetBeansProjects/App/src/com/jullio/advisor/wAsyncChat.java:87: error: cannot access JsonParseException
return mapper.readValue(data, Message.class);
class file for org.codehaus.jackson.JsonParseException not found
/home/mofa/NetBeansProjects/App/src/com/jullio/advisor/wAsyncChat.java:68: error: cannot access ObjectCodec
return mapper.writeValueAsString(data);
class file for org.codehaus.jackson.ObjectCodec not found
Here is the androidchat code:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.atmosphere.wasync.ClientFactory;
import org.atmosphere.wasync.Decoder;
import org.atmosphere.wasync.Encoder;
import org.atmosphere.wasync.Event;
import org.atmosphere.wasync.Function;
import org.atmosphere.wasync.Request;
import org.atmosphere.wasync.RequestBuilder;
import org.atmosphere.wasync.impl.AtmosphereClient;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.Date;
public class wAsyncChat extends Activity {
private Button bt;
private TextView tv;
private String serverIpAddress = "http://10.0.2.2:8080";
private final static ObjectMapper mapper = new ObjectMapper();
private final Handler uiHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
AtmosphereClient client = ClientFactory.getDefault().newClient(AtmosphereClient.class);
RequestBuilder request = client.newRequestBuilder()
.method(Request.METHOD.GET)
.uri(serverIpAddress + "/chat")
.trackMessageLength(true)
.encoder(new Encoder<Message, String>() {
#Override
public String encode(Message data) {
try {
return mapper.writeValueAsString(data);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
})
.decoder(new Decoder<String, Message>() {
#Override
public Message decode(Event type, String data) {
data = data.trim();
// Padding
if (data.length() == 0) {
return null;
}
if (type.equals(Event.MESSAGE)) {
try {
return mapper.readValue(data, Message.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
})
.transport(Request.TRANSPORT.WEBSOCKET);
final org.atmosphere.wasync.Socket socket = client.create();
socket.on("message", new Function<Message>() {
#Override
public void on(final Message t) {
uiHandler.post(new Runnable() {
#Override
public void run() {
Date d = new Date(t.getTime());
tv.append("Author " + t.getAuthor() + "# " + d.getHours() + ":" + d.getMinutes() + ": " + t.getMessage() + "\n");
}
});
}
}).on(new Function<Throwable>() {
#Override
public void on(Throwable t) {
tv.setText("ERROR 3: " + t.getMessage());
t.printStackTrace();
}
}).open(request.build());
bt.setOnClickListener(new OnClickListener() {
String name = null;
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
if (name == null) {
name = str;
}
socket.fire(new Message(name, str));
et.setText("");
Log.d("Client", "Client sent message");
} catch (Throwable e) {
tv.setText("ERROR 3: " + e.getMessage());
e.printStackTrace();
}
}
});
} catch (Throwable e) {
tv.setText("Unable to connect: " + e.getMessage());
e.printStackTrace();
}
}
}
I have the library for nodeserver connection. You can use it from git
SocketIO socketio = new SocketIO() {
#Override
public void onConnect() {
}
#Override
public void onDisconnect() {
}
#Override
public void onMessage(String message) {
Log.d("===Server Answer====",message);
}
};
socketio.Connect("192.168.0.1", 9000);
after onConnect() send the message:
socketio.send("Your message to socket");
it work with latest socketIO, and use RFC 6455 websocket protocol
I've recently read about XMPP and I would like to make an application which can send and receive IM messages so that I could get some experience with using XMPP. The problem is I hardly know anything about using XMPP or about using it with Android. I was wondering if someone could point me in the right direction on how to use XMPP with Android.
Thanks!
Well to start with XMPP you have to
Install OpenFire (The chat server)
Add the smack.jar XMPP client jar into the Android app
Implement the PacketListener like such
public class MyPacketListener implements PacketListener {
#Override
public void processPacket(Packet packet) {
// Write the implementation code here.
//The packet contains the message and the metadata about the message.
}
}
4.Next you need to implement the to handle the connection fail gracefully as such.
public class XMPPConnectionFailedException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public String toString() {
return "The Chat server or the Connection to the chat server failed";
}
}
5.Next you would need the class that actually does the connecting to the XMPP server and here is a implementations
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smackx.PrivateDataManager;
import com.test.chat.MyPacketListener;
import com.testchat.exception.XMPPConnectionFailedException;
public class ChatUtil {
public final static String SERVER_HOST = "serverip";
public final static int SERVER_PORT = 5222;
public final static String SERVICE_NAME = "p2547738.pubip.serverbeach.com";
private static XMPPConnection xmppConnection;
public static String CURRENT_RECIPIENT_CHAT_ID;
public static String CURRENT_RECIPIENT_NAME;
public static final String IN = "IN";
public static final String OUT = "OUT";
public static String CURRENT_RECIPIENT_FB_IMAGE;
public static boolean STARTED = false;
public static XMPPConnection getXmppConnection(String username) throws XMPPConnectionFailedException {
try {
if (xmppConnection == null) {
ConnectionConfiguration config = new ConnectionConfiguration(SERVER_HOST, SERVER_PORT, SERVICE_NAME);
xmppConnection = new XMPPConnection(config);
}
if (!xmppConnection.isConnected()) {
xmppConnection.connect();
}
if (!xmppConnection.isAuthenticated()) {
xmppConnection.login(username, "123");
ProviderManager pm = ProviderManager.getInstance();
pm.addIQProvider("query", "jabber:iq:private",new PrivateDataManager.PrivateDataIQProvider());
PacketFilter packetFilter = new MessageTypeFilter(Message.Type.chat);
xmppConnection.addConnectionListener(new ConnectionListener() {
#Override
public void reconnectionSuccessful() {
System.out.println("reconnectionSuccessful");
}
#Override
public void reconnectionFailed(Exception arg0) {
System.out.println("reconnectionFailed");
}
#Override
public void reconnectingIn(int arg0) {
System.out.println("reconnectingIn");
}
#Override
public void connectionClosedOnError(Exception arg0) {
System.out.println("connectionClosedOnError");
}
#Override
public void connectionClosed() {
System.out.println("connectionClosed");
}
});
MyPacketListener listener = new MyPacketListener();
xmppConnection.addPacketListener(shareFareChatListener,packetFilter);
}
Presence presence = new Presence(Presence.Type.available);
xmppConnection.sendPacket(presence);
ChatUtil.STARTED = true;
} catch (Exception e) {
throw new XMPPConnectionFailedException();
}
return xmppConnection;
}
}
6.Finally you try to connect your to the XMPP server using the credentials you used to sign users up as such
private void connectToChat(final String nickname) {
System.out.println("Connect to chat ...");
class ConnectToChatAsync extends AsyncTask {
#Override
protected Integer doInBackground(Context... params) {
try {
Listener.currentActivity = context;
ChatUtil.getXmppConnection(nickname);
return SERVER_SUCCESS_RESPONSE;
}
catch ( XMPPConnectionFailedException e) {
System.err.println("XMPPConnectionFailedException : " + e);
}
return CONNECTIVITY_PROBLEM;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if(result == CONNECTIVITY_PROBLEM){
// ApplicationDialog.showFeedBackDialog(ProjectConstants.XMPP_CHAT_FAILED, context);
}
}
}
new ConnectToChatAsync().execute();
}
That should settle you Programatically, all you got to do is Setup the Openfire Environment.
These links should help you out on that department
Create Your Own Jabber-Based Server That Works With iChat or Any Jabber Client
DIY: Set up the Openfire internal chat server
We are trying to access skydrive using phonegap.We used an activity to call login function of skydrive. But it does not call login function at all.
Would be great help if someone shed light on this.
Here is the code.
Here activity is called from plugin class of phonegap
Intent i = new Intent(myac, DispAct.class);
try{
System.out.println("before start activity");
//i.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
( this.cordova.getActivity()).startActivity(i);
}
catch(Exception e){ System.out.println("in catch"+e);}
Below code is the called activity
package org.apache.cordova;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
import com.microsoft.live.R;
public class DispAct extends Activity
{
log obj;
private Object cordova;
private static final String APP_CLIENT_ID ="00000000400D893E" ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("disp on create");
}
#Override
protected void onStart() {
super.onStart();
System.out.println("disp on start");
obj=new log();
obj.auth = new LiveAuthClient(this.getApplicationContext(), APP_CLIENT_ID);
Iterable<String> scopes = Arrays.asList("wl.basic","wl.signin","wl.skydrive","wl.skydrive_update");
obj.auth.login(this,scopes,obj);//********this is the function which has to call login page but does not work
System.out.println("disp after login");
}
#Override
public void onResume()
{
super.onResume();
//finish();
}
}
final class log implements LiveAuthListener{
String type,message;
LiveConnectClient client;
LiveAuthClient auth;
//Parcel out;
public log()
{
//auth=new LiveAuthClient(this, message);
}
synchronized public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
if(status == LiveStatus.CONNECTED) {
// this.resultTextView.setText("Signed in.");
System.out.println("IN SUCCess");
client = new LiveConnectClient(session);
//download(0);
notify();
}
else {
//this.resultTextView.setText("Not signed in.");
type="ERROR";
message="Not Connected";
client = null;
System.out.println("IN complete err");
notify();
}
}
synchronized public void onAuthError(LiveAuthException exception, Object userState) {
//this.resultTextView.setText("Error signing in: " + exception.getMessage());
client = null;
//type="ERROR";
//message="Error logging in";
System.out.println("IN error");
notify();
}
}
Here activity is displayed but login page does not appear which should appear as the result of login function