I am working on websocket connection to communicate with server.
Now, we have established a connection and able to send and receive message using Autobahn library.
Here is the code:
private void start() {
// wsuri is the url which has to be hit for connecting to the server i.e
// "ws://hostname:port "
final String wsuri = "ws://" + mHostname.getText() + ":"
+ mPort.getText();
// showing status on the UI.
mStatusline.setText("Status: Connecting to " + wsuri + " ..");
// enabling disconnect button clicking on which the connection will be
// disconnected.
setButtonDisconnect();
try {
mConnection.connect(wsuri, new WebSocketConnectionHandler() {
#Override
public void onOpen() {
// If connection is open, then status will be updated to
// "connected to..."
mStatusline.setText("Status: Connected to " + wsuri);
savePrefs();
// enabling mSendMessage button and mMessage edit Text.
mSendMessage.setEnabled(true);
mMessage.setEnabled(true);
}
#Override
public void onTextMessage(String payload) {
Log.d("ss", payload);
alert(payload);
}
#Override
public void onClose(int code, String reason) {
// If connection is lost, alert will be shown connection is
// lost and status will be set to "Ready".
alert("Connection lost.");
mStatusline.setText("Status: Ready.");
setButtonConnect();
// disabling mSendMessage button and mMessage edit Text.
mSendMessage.setEnabled(false);
mMessage.setEnabled(false);
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
We just have a single method onTextMessage(String payload) to handle response from server.
and to send message to server we use mConnection.sendTextMessage(mMessage.getText().toString());
But now we are facing issue that how to hit api on that server?or lets say I want some list of devices or device_Status etc how it will happen??
Any idea how to do that?? At present I am thinking of sending some "key":"pair" value in message in form of json, by which the server will identify what request I have made...
I am still not sure whether this is the right way? Please if somebody can help me in this.
Related
I have setup pubnub on android using java
And on all other Operating Systems the setup works fine. On Android P however the attach listener always gives this error -
PNStatus(category=PNBadRequestCategory, errorData=PNErrorData(information=null, throwable=PubNubException(errormsg=CLEARTEXT communication to ps.pndsn.com not permitted by network security policy, pubnubError=PubNubError(errorCode=103, errorCodeExtended=0, errorObject=null, message=HTTP Error. Please check network connectivity. Please contact support with error details if issue persists., errorString=null), jso=null, response=null, statusCode=0)), error=true, statusCode=0, operation=PNSubscribeOperation, tlsEnabled=false, uuid=null, authKey=null, origin=null, clientRequest=null, affectedChannels=[5d67fb36f4f95718bf8ec310], affectedChannelGroups=[])
The setup is as follows -
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setLogVerbosity(PNLogVerbosity.BODY);
pnConfiguration.setPublishKey(getString(R.string.pubnub_publish_key));
pnConfiguration.setSubscribeKey(getString(R.string.pubnub_subscribe_key));
pnConfiguration.setSecure(false);
pubnub = new PubNub(pnConfiguration);
Then i attach listener like this
pubnub.addListener(new SubscribeCallback() {
#Override
public void status(PubNub pubnub, PNStatus status) {
Log.e("Pubnub:- ", status.toString());
switch (status.getOperation()) {
// let's combine unsubscribe and subscribe handling for ease of use
case PNSubscribeOperation:
case PNUnsubscribeOperation:
// note: subscribe statuses never have traditional
// errors, they just have categories to represent the
// different issues or successes that occur as part of subscribe
switch (status.getCategory()) {
case PNConnectedCategory:
// this is expected for a subscribe, this means there is no error or issue whatsoever
case PNReconnectedCategory:
// this usually occurs if subscribe temporarily fails but reconnects. This means
// there was an error but there is no longer any issue
case PNDisconnectedCategory:
// this is the expected category for an unsubscribe. This means there
// was no error in unsubscribing from everything
case PNUnexpectedDisconnectCategory:
// this is usually an issue with the internet connection, this is an error, handle appropriately
case PNAccessDeniedCategory:
// this means that PAM does allow this client to subscribe to this
// channel and channel group configuration. This is another explicit error
default:
// More errors can be directly specified by creating explicit cases for other
// error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory`
}
case PNHeartbeatOperation:
// heartbeat operations can in fact have errors, so it is important to check first for an error.
// For more information on how to configure heartbeat notifications through the status
// PNObjectEventListener callback, consult <link to the PNCONFIGURATION heartbeart config>
if (status.isError()) {
// There was an error with the heartbeat operation, handle here
} else {
// heartbeat operation was successful
}
default: {
// Encountered unknown status type
}
}
}
#Override
public void message(PubNub pubnub, PNMessageResult message) {
String messagePublisher = message.getPublisher();
System.out.println("Message publisher: " + messagePublisher);
System.out.println("Message Payload: " + message.getMessage());
System.out.println("Message Subscription: " + message.getSubscription());
System.out.println("Message Channel: " + message.getChannel());
System.out.println("Message timetoken: " + message.getTimetoken());
}
#Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
#Override
public void signal(PubNub pubnub, PNSignalResult pnSignalResult) {
System.out.println("Signal publisher: " + signal.getPublisher());
System.out.println("Signal payload: " + signal.getMessage());
System.out.println("Signal subscription: " + signal.getSubscription());
System.out.println("Signal channel: " + signal.getChannel());
System.out.println("Signal timetoken: " + signal.getTimetoken());
}
#Override
public void user(PubNub pubnub, PNUserResult pnUserResult) {
// for Objects, this will trigger when:
// . user updated
// . user deleted
PNUser pnUser = pnUserResult.getUser(); // the user for which the event applies to
pnUserResult.getEvent(); // the event name
}
#Override
public void space(PubNub pubnub, PNSpaceResult pnSpaceResult) {
// for Objects, this will trigger when:
// . space updated
// . space deleted
PNSpace pnSpace = pnSpaceResult.getSpace(); // the space for which the event applies to
pnSpaceResult.getEvent(); // the event name
}
#Override
public void membership(PubNub pubnub, PNMembershipResult pnMembershipResult) {
// for Objects, this will trigger when:
// . user added to a space
// . user removed from a space
// . membership updated on a space
JsonElement data = pnMembershipResult.getData(); // membership data for which the event applies to
pnMembershipResult.getEvent(); // the event name
}
#Override
public void messageAction(PubNub pubnub, PNMessageActionResult pnActionResult) {
PNMessageAction pnMessageAction = pnActionResult.getAction();
System.out.println("Message action type: " + pnMessageAction.getType());
System.out.println("Message action value: " + pnMessageAction.getValue());
System.out.println("Message action uuid: " + pnMessageAction.getUuid());
System.out.println("Message action actionTimetoken: " + pnMessageAction.getActionTimetoken());
System.out.println("Message action messageTimetoken: " + pnMessageAction.getMessageTimetoken());]
System.out.println("Message action subscription: " + pnActionResult.getSubscription());
System.out.println("Message action channel: " + pnActionResult.getChannel());
System.out.println("Message action timetoken: " + pnActionResult.getTimetoken());
}
});
Like i said it works fine in other OS's except 9 and i am using the latest version of pubnub, infact i upgraded to the latest version and the above error was identical.
And i noticed something else, a message which i see in the debugger that only shows up when running in android version 9.
isWhitelistProcess - Process is Whitelisted
I searched for the message and found that its a harmless warning message.
Enabling TLS (SSL) resolves this error:
pnConfiguration.setSecure(true);
The reason is answered in another Stack Overflow thread already. It is not specific to PubNub but because you disabled TLS (SSL) in PubNub, it explicitly called out the PubNub domain in the error.
I have offline messages option enabled in the openfire server.But I'm unable to get offline messages
User A is online ,User B is online ,in this case I'm able to get messages.
Now User B Turned off his WiFi(Note : User A waited till the user B Session completely killed in the server )
now User A send a message to User B
in this case I'm able to see the message in the openfire offline table.
Now User B Comes online again server is sending the message to user B as the server come to know that User B is online
(Message disappeared from offline messages table ).
But User B is not going to receive that message.
connection.login(userName, userPwd, UiUtility.getMyPhoneNO());
PacketFilter filter = new PacketTypeFilter(org.jivesoftware.smack.packet.Message.class);
packetListener =new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message
.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody()
+ "] from [" + fromName + "]");
}
}
};
connection.addPacketListener(packetListener, filter);
Again after successful login im able to chat normally.But I wonder why those offline messages are missing ? .My PacketListener unable to catch those offline messages .Please Help me
Asmack is depreceated. Use Smack. An Open Source XMPP Client Library written in Java for JVMs and Android. Add the following lines to your gradle file:
compile 'org.igniterealtime.smack:smack-android:4.1.3'
compile 'org.igniterealtime.smack:smack-tcp:4.1.3'
compile 'org.igniterealtime.smack:smack-extensions:4.1.3'
The problem is easy to be solved.
Before making connection with the XMPP server just register providers using ProviderManager class provided by ASmack library.
If this can't solve ur problem visit ur local server and search for offline messages, and select the option ALWAYS STORE setting the storage limit to be 1000 kb. It is 100 kb by default.
Hope this works.
After lot struggle, I have resolved the issue. In your openfire admin page, go to "client settings" and reduce the idle time from 360sec (by default) to 1 sec(may be). Only then when you disconnected from Internet, it can detect that you are offline and preserve rest of the messages as OFFLINE.
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if(isConnected){
new Thread() {
public void run() {
try {
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
builder.setUsernameAndPassword("phone", "admin");
builder.setSendPresence(true);
builder.setServiceName(<Service name>);
builder.setHost(<Host name>);
builder.setResource("Test");
builder.setDebuggerEnabled(true);
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("Available");
connection = new XMPPTCPConnection(builder.build());
connection.connect();
connection.login();
Presence presence123 = new Presence(Presence.Type.available);
presence123.setStatus("Available");
try {
connection.sendStanza(presence123);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
StanzaFilter filter = new AndFilter(new StanzaTypeFilter(Message.class));
PacketListener myListener = new PacketListener()
{
public void processPacket(Stanza stanza)
{
retrieveMessage(stanza,userType);
}
};
connection.addPacketListener(myListener, filter);
try {
connection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
} catch (SmackException | XMPPException | IOException e) {
e.printStackTrace();
}
//return connection.isConnected();
}
}.start();
The above is working fine and able to retrieve the offline messages. The method "retrieveMessage(stanza,userType);" is used to process the incoming message and update the Adapter. Make sure to send the Presence as "Available" when you reconnect. Please let me know if there are still any issues.
I have finished developing my IM application on android (using xmpp & GCM), and I am using the gcm for buth UpPayload and DownPayloads..
and to notify the user that his partner is online/ofline I send messaage that my xmpp server "understand"
that tell the statuse.
protected void onStart() {
super.onStart();
if(!isOnlineSent)
{SendOnlineStatus("Online");
isOnlineSent=true;}
.
.
.
.}
and the SendOnlineStatus look like:
Intent OnlineMsg = new Intent();
OnlineMsg.putExtra("action", "com.Esmaeel.sodfarim.sodfa01.MESSAGE");
String nowtime = String.valueOf(EsTools.getCurrentTime());
OnlineMsg.putExtra(ConstantsGCM.TYPECLM, ConstantsGCM.ONST);
OnlineMsg.putExtra(ConstantsGCM.STATUS_on_of, Status);
OnlineMsg.putExtra(ConstantsGCM.TO_CLM, "-01");
OnlineMsg.putExtra(ConstantsGCM.FROMCLM, UUID);
OnlineMsg.putExtra(ConstantsGCM.MESSAGE_ID_CLM, regid + nowtime);
OnlineMsg.putExtra(ConstantsGCM.NAME_CLM, "Name");
final Bundle bndl = OnlineMsg.getExtras();
new AsyncTask() {
#Override
protected String doInBackground(Object[] objects) {
if (ggcm == null) {
ggcm = GoogleCloudMessaging.getInstance(context);
}
try {
ggcm.send(PRO_ID + ConstantsGCM.GCM_SERVER, bndl.getString(ConstantsGCM.MESSAGE_ID_CLM), bndl); //// GCM_SERVER="gcm.googleapis.com"
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}.execute(null, null, null);
the server checks the value of
payload.get(ConstantsGCM.TYPECLM);
if the type ONST the server reads the value payload.get(ConstantsGCM.STATUS_on_of);
the valid valuse of payload.get(ConstantsGCM.STATUS_on_of); is "online" OR "offline".
then the server update the user status and sends the new status to all the user's friends.
the same I do with Typing status but the last step I send just to the other side of the active chat.
but I get problems like "user apear online while he is offline, and some times apears typing when he is not.
any help or more effictive Ideas?
I don't know for the typing part, but for the status, maybe you should only send to the friends something like : "you should check the status of this user" then each friends phone will get the real status directly on the server. Hope it helps
I am creating a generic Chromecast remote control app. Most of the guts of the app are already created and I've managed to get Chromecast volume control working (by connecting to a Chromecast device along side another app that is casting - YouTube for example).
What I've having difficult with is performing other media commands such as play, pause, seek, etc.
Use case example:
1. User opens YouTube on their android device and starts casting a video.
2. User opens my app and connects to the same Chromecast device.
3. Volume control from my app (works now)
4. Media control (play, pause, etc) (does not yet work)
I found the Cast api reference that explains that you can sendMessage(ApiClient, namespace, message) with media commands; however the "message" (JSON) requires the sessionId of the current application (Youtube in this case). I have tried the following, but the connection to the current application always fails; status.isSuccess() is always false:
Cast.CastApi
.joinApplication(mApiClient)
.setResultCallback(
new ResultCallback<Cast.ApplicationConnectionResult>() {
#Override
public void onResult(
Cast.ApplicationConnectionResult result) {
Status status = result.getStatus();
if (status.isSuccess()) {
ApplicationMetadata applicationMetadata = result
.getApplicationMetadata();
sessionId = result.getSessionId();
String applicationStatus = result
.getApplicationStatus();
boolean wasLaunched = result
.getWasLaunched();
Log.i(TAG,
"Joined Application with sessionId: "
+ sessionId
+ " Application Status: "
+ applicationStatus);
} else {
// teardown();
Log.e(TAG,
"Could not join application: "
+ status.toString());
}
}
});
Is is possible to get the sessionId of an already running cast application from a generic remote control app (like the one I am creating)? If so, am I right in my assumption that I can then perform media commands on the connected Chromecast device using something like this:
JSONObject message = new JSONObject();
message.put("mediaSessionId", sessionId);
message.put("requestId", 9999);
message.put("type", "PAUSE");
Cast.CastApi.sendMessage(mApiClient,
"urn:x-cast:com.google.cast.media", message.toString());
Update:
I have tried the recommendations provided by #Ali Naddaf but unfortunately they are not working. After creating mRemoteMediaPlayer in onCreate, I also do requestStatus(mApiClient) in the onConnected callback (in the ConnectionCallbacks). When I try to .play(mApiClient) I get an IllegalStateException stating that there is no current media session. Also, I tried doing joinApplication and in the callback performed result.getSessionId; which returns null.
A few comments and answers:
You can get the sessionId from the callback of launchApplication or joinApplication; in the "onResult(result)", you can get the sessionId from: result.getSessionId()
YouTube is still not on the official SDK so YMMV, for apps using official SDK, you should be able to use the above approach (most of it)
Why are you trying to set up a message yourself? Why not building a RemoteMediaPlayer and using play/pause that is provided there? Whenever you are working with the media playback through the official channel, always use the RemoteMediaPlayer (don't forget to call requestStatus() on it after creating it).
Yes it is possible , First you have to save sesionId and CastDevice device id
and when remove app from background and again open app please check is there sessionId then call bello line.
Cast.CastApi.joinApplication(apiClient, APP_ID,sid).setResultCallback(connectionResultCallback);
if you get success result then need to implement further process in connectionResultCallback listener.
//Get selected device which you selected before
#Override
public void onRouteAdded(MediaRouter router, MediaRouter.RouteInfo route) {
// Log.d("Route Added", "onRouteAdded");
/* if (router.getRoutes().size() > 1)
Toast.makeText(homeScreenActivity, "'onRouteAdded :: " + router.getRoutes().size() + " -- " + router.getRoutes().get(1).isSelected(), Toast.LENGTH_SHORT).show();
else
Toast.makeText(homeScreenActivity, "'onRouteAdded :: " + router.getRoutes(), Toast.LENGTH_SHORT).show();*/
if (router != null && router.getRoutes() != null && router.getRoutes().size() > 1) {
// Show the button when a device is discovered.
// Toast.makeText(homeScreenActivity, "'onRouteAdded :: " + router.getRoutes().size() + " -- " + router.getRoutes().get(1).isSelected(), Toast.LENGTH_SHORT).show();
mMediaRouteButton.setVisibility(View.VISIBLE);
titleLayout.setVisibility(View.GONE);
castName.setVisibility(View.VISIBLE);
selectedDevice = CastDevice.getFromBundle(route.getExtras());
routeInfoArrayList = router.getRoutes();
titleLayout.setVisibility(View.GONE);
if (!isCastConnected) {
String deid = MyPref.getInstance(homeScreenActivity).readPrefs(MyPref.CAST_DEVICE_ID);
for (int i = 0; i < routeInfoArrayList.size(); i++) {
if (routeInfoArrayList.get(i).getExtras() != null && CastDevice.getFromBundle(routeInfoArrayList.get(i).getExtras()).getDeviceId().equalsIgnoreCase(deid)) {
selectedDevice = CastDevice.getFromBundle(routeInfoArrayList.get(i).getExtras());
routeInfoArrayList.get(i).select();
ReSelectedDevice(selectedDevice, routeInfoArrayList.get(i).getName());
break;
}
}
}
}
}
//Reconnect google Api Client
public void reConnectGoogleApiClient() {
if (apiClient == null) {
Cast.CastOptions apiOptions = new
Cast.CastOptions.Builder(selectedDevice, castClientListener).build();
apiClient = new GoogleApiClient.Builder(this)
.addApi(Cast.API, apiOptions)
.addConnectionCallbacks(reconnectionCallback)
.addOnConnectionFailedListener(connectionFailedListener)
.build();
apiClient.connect();
}
}
// join Application
private final GoogleApiClient.ConnectionCallbacks reconnectionCallback = new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
// Toast.makeText(homeScreenActivity, "" + isDeviceSelected(), Toast.LENGTH_SHORT).show();
try {
String sid = MyPref.getInstance(homeScreenActivity).readPrefs(MyPref.CAST_SESSION_ID);
String deid = MyPref.getInstance(homeScreenActivity).readPrefs(MyPref.CAST_DEVICE_ID);
if (sid != null && deid != null && sid.length() > 0 && deid.length() > 0)
Cast.CastApi.joinApplication(apiClient, APP_ID, sid).setResultCallback(connectionResultCallback);
isApiConnected = true;
} catch (Exception e) {
}
}
#Override
public void onConnectionSuspended(int i) {
isCastConnected = false;
isApiConnected = false;
}
};
I am using quickblox api for video chat and i want to get online available user .I know that it can be done through roster but i don't know how to get roster and how to add entries in roster .i want this through quickblox connection and dont know how to get xmpp connection.
XMPPConnection.addConnectionCreationListener(new ConnectionCreationListener() {
#Override
public void connectionCreated(Connection arg0) {
Log.i(TAG, "receive xmpp connection : " + arg0);
connection = arg0;
roster = arg0.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
Presence presence;
Log.e(TAG, "user count" + entries.size());
for (RosterEntry entry : entries) {
presence = roster.getPresence(entry.getUser());
Log.i(TAG, "" + entry.getUser());
Log.i(TAG, "" + presence.getType().name());
Log.i(TAG, "" + presence.getStatus());
}
}
});
So at the start of your program register that XMPPConnection listener, usually it take few seconds to receive connection object.
But it will work only if you will use creatEntry only in that case rooster will see those created users.
To creat entry using Roster use next code:
try {
rooster.createEntry("name", "user_id", null);
} catch (XMPPException e) {
e.printStackTrace();
}
I didn't use any group, and with success see user on second device.