i'm using smack 4.1 library where i'm unable to revived message event.
here is my code-
Chat chat = connection.getChatManager().createChat("user2#openfireserver", new MessageListener() {
#Override
public void processMessage(Chat arg0, Message arg1) {
System.out.println(arg1.getBody());
}
});
chat.sendMessage("test message");
debug report-
<message id="WrfOv-14" to="user1#openfireserver/Smack" from="user2#openfireserver/Smack" type="chat"><body>my test application</body><thread>56b1a75c-69a5-4a12-b12a-d24e072a2ce7</thread></message>
receive chat show in debug but not getting event in processMessage method.
(may my question is duplicate but i'm not find relevant answer)
I have used Smack 4.1 library in one of my Android projects. The following code snippet worked for me.
ChatManager.getInstanceFor(connection).addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat || message.getType() == Message.Type.normal) {
if(message.getBody()!=null) {
Toast.makeText(this,message.getFrom() + " : " + message.getBody(),Toast.LENGTH_LONG).show();
}
}
}
});
}
});
Here is an example for smack-4.1.0-beta3-SNAPSHOT-2015-02-09:
It works for me, try it.
private void onAutthenticated() {
ChatManager.getInstanceFor(mConnection).addChatListener(ChatConnection.this);
}
#Override
public void chatCreated(Chat chat, boolean b) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
if (message.getType().equals(Message.Type.chat) || message.getType().equals(Message.Type.normal)) {
Log.d(TAG, message.getFrom());
Log.d(TAG, message.getBody());
}
}
});
}
For Receiving any Type of Message, you can use following code
StanzaTypeFilter message_filter = new StanzaTypeFilter(Message.class);
connection.addSyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws NotConnectedException {
Message message = (Message)packet;
if(message.getType() == Message.Type.chat) {
//single chat message
} else if(message.getType() == Message.Type.groupchat) {
//group chat message
} else if(message.getType() == Message.Type.error) {
//error message
}
}
}, message_filter);
I think the create methord and the add methord are not same. create methord does not register a listener,but the add methord does register.When I see the api doc, I have the same question with you,but the doc does not give me an answer.So i guess this may be where the problem exists.
Related
I am working with XMPP chatting application and i successfully integrated the chatting using XMPP, BUT now my requirement is to handle other type of message type='headline'
So when i receive this type of message then processMessage never called.
MMessageListener.class
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
Log.e(TAG, "message type : " + message.getType());
}
}
ChatManagerListenerImpl.class
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,
final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
I am stuck with this issue, please suggest
Thanks
I am trying to create a simple android app that controls my robot. All the communication is done using mqtt and eclipse paho for android, but I am very new to the protocol. I cannot find a simple explanation of how to get data from a subscribed topic. The best one I found was HiveMQ android tutorial
but that did not explain how to get the data from the callbacks. Any assistance would be appreciated.
For android I have used Paho Android project, very simple to use, here are the steps:
Intialize a client, set required options and connect.
MqttAndroidClient mqttClient = new MqttAndroidClient(BaseApplication.getAppContext(), broker, MQTT_CLIENT_ID);
//Set call back class
mqttClient.setCallback(new MqttCallbackHandler(BaseApplication.getAppContext()));
MqttConnectOptions connOpts = new MqttConnectOptions();
IMqttToken token = mqttClient.connect(connOpts);
Subscribe to a topic.
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken arg0) {
mqttClient.subscribe("TOPIC_NAME" + userId, 2, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(LOG_TAG, "Successfully subscribed to topic.");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(LOG_TAG, "Failed to subscribed to topic.");
}
});
}
#Override
public void onFailure(IMqttToken arg0, Throwable arg1) {
Log.d(LOG_TAG, errorMsg);
}
});
Define your callback handler class.
public class MqttCallbackHandler implements MqttCallbackExtended {
#Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Anjing", mqttMessage.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
}
Also set following in manifest file.
<service android:name="org.eclipse.paho.android.service.MqttService" >
</service>
Would recommend visiting their project on GitHub and going through samples online.
Eclipse Paho Android
Hoping this helps. If you have more questions please visit
Android step by step guide using Eclipse Paho
Cheers !
I am trying to develop a chat application but instead of Google message service I tried writing xmmp node server.
I am able to login in to server.But getting message saying feature not implemented.
<iq to='359648069251166#10.10.25.126/Smack' id='cu03M-5' type='error'><error type='cancel'><feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></iq>
android code
final TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setServiceName(IPADRESS)
.setHost(IPADRESS)
.setPort(5222)
.build();
AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
conn2.setPacketReplyTimeout(1000);
SmackConfiguration.DEBUG = true;
conn2.connect();
conn2.addConnectionListener(new ConnectionListener() {
#Override
public void connected(XMPPConnection connection) {
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
}
#Override
public void connectionClosed() {
}
#Override
public void connectionClosedOnError(Exception e) {
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int seconds) {
}
#Override
public void reconnectionFailed(Exception e) {
}
});
conn2.addAsyncPacketListener(new PacketListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
if (packet != null) {
Log.d("stanza", "received" + packet.toXML());
Toast.makeText(getApplicationContext(), packet.toXML(), Toast.LENGTH_LONG).show();
}
}
}, new PacketFilter() {
#Override
public boolean accept(Stanza packet) {
return true;
}
});
Roster roster = Roster.getInstanceFor(conn2);
//Get all rosters
Collection<RosterEntry> entries = roster.getEntries();
//loop through
for (RosterEntry entry : entries) {
//example: get presence, type, mode, status
Presence entryPresence = roster.getPresence(entry.getUser());
Presence.Type userType = entryPresence.getType();
Presence.Mode mode = entryPresence.getMode();
String status = entryPresence.getStatus();
Log.d("stanza",userType+" "+status);
}
roster.addRosterListener(new RosterListener() {
#Override
public void presenceChanged(Presence presence) {
//Called when the presence of a roster entry is changed
}
#Override
public void entriesUpdated(Collection<String> arg0) {
// Called when a roster entries are updated.
}
#Override
public void entriesDeleted(Collection<String> arg0) {
// Called when a roster entries are removed.
}
#Override
public void entriesAdded(Collection<String> arg0) {
// Called when a roster entries are added.
}
});
conn2.login(mngr.getDeviceId(), "secret");
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("I’m available");
conn2.sendPacket(presence);
ChatManager chatManager = ChatManager.getInstanceFor(conn2);
Chat chat = chatManager.createChat(mngr.getDeviceId(), new ChatMessageListener() {
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
Log.d("stanza", message.toString());
// processMessage(chatMessage);
}
}
});
// Add a packet listener to get messages sent to us
Message message = new Message();
message.setFrom(mngr.getDeviceId());
message.setTo(mngr.getDeviceId());
message.setType(Message.Type.chat);
message.setSubject("jhelloworld");
chat.sendMessage(message);
}catch (Exception e){
Log.d("error",e.getMessage());
}
I took server from here.
server side code.
var startServer = function (done) {
// Sets up the server.
server = new xmpp.C2S.TCPServer({
port: 5222,
domain: 'localhost'
})
server.on('connection', function (client) {
// That's the way you add mods to a given server.
// Allows the developer to register the jid against anything they want
client.on('register', function (opts, cb) {
console.log('REGISTER')
cb(true)
})
// Allows the developer to authenticate users against anything they want.
client.on('authenticate', function (opts, cb) {
console.log('server:', opts.username, opts.password, 'AUTHENTICATING')
if (opts.password === 'secret') {
console.log('server:', opts.username, 'AUTH OK')
cb(null, opts)
} else {
console.log('server:', opts.username, 'AUTH FAIL')
cb(false)
}
})
client.on('online', function () {
console.log('server:', client.jid.local, 'ONLINE')
client.send("")
})
// Stanza handling
client.on('stanza', function (stanza) {
console.log('server:', client.jid.local, 'stanza', stanza.toString())
var from = stanza.attrs.from
stanza.attrs.from = stanza.attrs.to
stanza.attrs.to = from
client.send(stanza)
})
// Stanza handling
client.on('chat', function (stanza) {
console.log('server:', client.jid.local, 'chat', stanza.toString())
client.send(stanza)
});
// On Disconnect event. When a client disconnects
client.on('disconnect', function () {
console.log('server:', client.jid.local, 'DISCONNECT')
})
})
server.on('listening', done)
}
startServer(function (){
console.log("server localhost started at 5222 localport");
});
I tried many solution from stackoverflow and smack community but didnt.
help will be appreciated.
When I am trying to call joinRoom() or createRoom() method.I am getting two different error
"registration-required(407)"
"feature-not-implemented(501) Will me done soon".
for reference purpose,I have posted code also.I already posted this issue on quickblox discussion board but nobody has solution.
QBChatService.getInstance().joinRoom(roomName, roomReceivingListener);
String roomName="myroom";
roomReceivingListener = new RoomListener()
{
#Override
public void onCreatedRoom(QBChatRoom qbChatRoom)
{
Log.i("TAG", "on Created Room listener");
chatRoom = qbChatRoom;
//chatRoom.addMessageListener(chatMessageListener);
}
#Override
public void onJoinedRoom(QBChatRoom qbChatRoom)
{
Log.i("TAG", "on Joined Room listener");
chatRoom = qbChatRoom;
//QBChatService.getInstance().joinRoom(chatRoom, roomReceivingListener);
//chatRoom.addMessageListener(chatMessageListener);
}
#Override
public void onError(String msg)
{
Log.i("TAG", "on join Room error listener");
}
};
Requirement of project: communication between windows azure Website and android device using azure mobile services
1)Website is build in VB.NET using Microsoft Windows Azure (server side)
2)Android Application is on Android Device (client side)
The client (Android user) should be able to send data from android device (client side) to Website (Server side) and vice-versa To make this possible i.e. Communcation Between client and sever I am using Mobile Services provided by Microsoft Windows Azure (server side) which use GCM (Google Cloud Messaging)
I have Followed all steps according to the documentation
http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-push-android/
Also followed all steps as been provided in the above link documentation of Microsoft windows azure
but when I try to send message from Android device towards the website the following error occurs
Error: com.microsoft.windowsazure.mobileservices.MobileServiceException: Error while processing request
Note: GCM (Google Cloud Messaging) gives us an gcm.jar file which is used in the android app to send data towards Server i.e website
ONCREATE CODE
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
mRegistationId = GCMRegistrar.getRegistrationId(this);
if (mRegistationId.equals("")) {
GCMRegistrar.register(this, SENDER_ID);
}
mProgressBar = (ProgressBar) findViewById(R.id.loadingProgressBar);
// Initialize the progress bar
mProgressBar.setVisibility(ProgressBar.GONE);
try {
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
mClient = new MobileServiceClient(
"url of website",
"POBHgxwAktyxUdeRRpcFyqEcsppwiS99",
this).withFilter(new ProgressFilter());
// Get the Mobile Service Table instance to use
mToDoTable = mClient.getTable(ToDoItem.class);
mTextNewToDo = (EditText) findViewById(R.id.textNewToDo);
// Create an adapter to bind the items with the view
mAdapter = new ToDoItemAdapter(this, R.layout.row_list_to_do);
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
listViewToDo.setAdapter(mAdapter);
// Load the items from the Mobile Service
refreshItemsFromTable();
}
catch (MalformedURLException e) {
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
}
On BUTTON click event addItem() is called
public void addItem(View view) {
if (mClient == null) {
return;
}
try
{
// Create a new item
ToDoItem item = new ToDoItem();
item.setText(mTextNewToDo.getText().toString());
item.setComplete(false);
// Insert the new item
mToDoTable.insert(item, new TableOperationCallback<ToDoItem>() {
public void onCompleted(ToDoItem entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
if (!entity.isComplete()) {
mAdapter.add(entity);
}
} else {
createAndShowDialog(exception, "Error");
}
}
});
item.setRegistrationId(mRegistationId.equals("") ?
GCMIntentService.getRegistrationId() : mRegistationId);
mTextNewToDo.setText("");
}
catch(Exception ex)
{
}
}
public void checkItem(ToDoItem item) {
if (mClient == null) {
return;
}
// Set the item as completed and update it in the table
item.setComplete(true);
mToDoTable.update(item, new TableOperationCallback<ToDoItem>() {
public void onCompleted(ToDoItem entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
if (entity.isComplete()) {
mAdapter.remove(entity);
}
} else {
createAndShowDialog(exception, "Error");
}
}
});
}
private void refreshItemsFromTable() {
// Get the items that weren't marked as completed and add them in the
// adapter
mToDoTable.where().field("complete").eq(val(false)).execute(new TableQueryCallback<ToDoItem>() {
public void onCompleted(List<ToDoItem> result, int count, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
mAdapter.clear();
for (ToDoItem item : result) {
mAdapter.add(item);
}
} else {
createAndShowDialog(exception, "Error");
}
}
});
}
private void createAndShowDialog(Exception exception, String title) {
createAndShowDialog(exception.toString(), title);
}
private void createAndShowDialog(String message, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
private class ProgressFilter implements ServiceFilter {
#Override
public void handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback,
final ServiceFilterResponseCallback responseCallback) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.VISIBLE);
}
});
nextServiceFilterCallback.onNext(request, new ServiceFilterResponseCallback() {
#Override
public void onResponse(ServiceFilterResponse response, Exception exception) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.GONE);
}
});
if (responseCallback != null) responseCallback.onResponse(response, exception);
}
});
}
}
Figured out that the tutorial is using ' instead of ", which in my case was the problem. The issue was in the Insert script on azure. Hope it helps you :-)