LoganSquare and Salut libraries - Android Wifip2p - android

I try to using salut librari (wifip2p library) for Android.
All work fine, discover devices, connect host, connect clients...
But when I need send a message, I have a problem.
I follow Salut tutorial: Salut
I send a message, and in console say me tha tthe message is received.
09-13 13:21:58.633 21798-21906/app.ingenia.marse.ingeniamarse D/Salut: Listening for service data...
09-13 13:21:58.643 21798-21986/app.ingenia.marse.ingeniamarse V/Salut: A device is sending data...
09-13 13:21:58.675 21798-21986/app.ingenia.marse.ingeniamarse D/Salut: Successfully received data.
But I can't read the received message.
The sender function:
public void sendData(){
Message myMessage = new Message();
myMessage.description = "See you on the other side!";
network.sendToAllDevices(myMessage, new SalutCallback() {
#Override
public void call() {
Log.e(TAG, "Oh no! The data failed to send.");
}
});
}
Where I received data:
#Override
public void onDataReceived(Object data) {
Log.d(TAG, "Received network data.");
try
{
Message newMessage = LoganSquare.parse((Message)data, Message.class);
Log.d(TAG, newMessage.description); //See you on the other side!
//Do other stuff with data.
}
catch (IOException ex)
{
Log.e(TAG, "Failed to parse network data.");
}
}
The code don't excecute the log received network data. And I need to change one line:
Message newMessage = LoganSquare.parse((Message)data, Message.class);
//to
Message newMessage = LoganSquare.parse(String.valueOf((Message)data), Message.class);
And the Message.class:
#JsonObject
public class Message{
/*
* Annotate a field that you want sent with the #JsonField marker.
*/
#JsonField
public String description;
/*
* Note that since this field isn't annotated as a
* #JsonField, LoganSquare will ignore it when parsing
* and serializing this class.
*/
public int nonJsonField;
#OnJsonParseComplete
void onParseComplete() {
Log.d("PARSED", "onParseComplete: PARSED!!");
}
/*
* Optional callback method to do something before your
* object serializes.
*/
#OnPreJsonSerialize
void onPreSerialize() {
Log.d("SERIALIZED", "onParseComplete: SERIALIZED!!");
}
}
The two logs in message.class nor they have executed

It is because according to documentation, onDataRecieve() is not executed as data.isEmpty() returns true. Check what i mean from here.

Related

Moto G5 Plus can't connect via Socket to a local server

I have an application where the smartphone must connect via SSLSocket to a local server. I tested my app on 5 different smartphones: Moto G2 (6.0), Redmi 3S (6.0.1), LG K5 (6.0), Moto G5 Plus (7.1.1) and OnePlus 5 (8.0). The Moto G5 Plus was the only one to show this problem.
This is the line that causes the problematic behaviour. All tests where done on the same network.
socket = (SSLSocket) sslContext.getSocketFactory().createSocket(serverAddress, serverPort);
Is there any known problem with Moto G5 Plus or with Android 7+ around this behaviour?
EDIT: Some more tests are leading to an idea of Android system trying to force the Socket to connect through mobile network when identifying that WiFi interface is connected, but with no internet. Is there any way to enforce the Socket to use WiFi instead of mobile network?
Disclaimer: I didn't test this so I'm really not sure if it works.
The Network class has a bind(Socket) method, maybe you could find the wifi network and then bind it to your socket. From the doc it seems that this is what you need, it says:
/**
* Binds the specified {#link Socket} to this {#code Network}. All data traffic on the socket
* will be sent on this {#code Network}, irrespective of any process-wide network binding set by
* {#link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
*/
The Socket shouldn't be connected before binding to the network, so I think you should create it with socketFactory.createSocket() and connect it only after the binding.
So, you should first find your Network (Kotlin):
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val wifiNetwork = connectivityManager.allNetworks.firstOrNull {
val info = connectivityManager.getNetworkInfo(it)
info.type == ConnectivityManager.TYPE_WIFI
}
or (Java)
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
Network wifiNetwork = null;
for(Network network : connectivityManager.getAllNetworks()){
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
wifiNetwork = network;
break;
}
}
Then bind it to the Socket and finally connect (Kotlin):
wifiNetwork?.bindSocket(socket)
val socketAddress = InetSocketAddress(hostname, port)
socket.connect(socketAddress)
or (Java)
if(wifiNetwork != null){
wifiNetwork.bindSocket(socket);
}
InetSocketAddress socketAddress = InetSocketAddress(hostName, port);
socket.connect(socketAddress);
Note, it needs ACCESS_NETWORK_STATE permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
i hope it helps you,i just found your solution on github.
for further details and for official link,please check this out, i think this can be helpful to you.
if it is not the answer,please ignore this answer.
We are using AsyncTask to avoid StrictMode fatal error for network access ( Look in references ). The StrictMode policy is simply forbidding us to affect on UI Thread.
/* AsyncTask class which manages connection with server app and is sending shutdown command.
*/
public class ShutdownAsyncTask extends AsyncTask<String, String, TCPClient> {
private static final String COMMAND = "shutdown -s" ;
private TCPClient tcpClient ;
private Handler mHandler ;
private static final String TAG = "ShutdownAsyncTask";
/**
* ShutdownAsyncTask constructor with handler passed as argument. The UI is updated via handler.
* In doInBackground(...) method, the handler is passed to TCPClient object.
* #param mHandler Handler object that is retrieved from MainActivity class and passed to TCPClient
* class for sending messages and updating UI.
*/
public ShutdownAsyncTask(Handler mHandler){
this.mHandler = mHandler;
}
/**
* Overriden method from AsyncTask class. There the TCPClient object is created.
* #param params From MainActivity class empty string is passed.
* #return TCPClient object for closing it in onPostExecute method.
*/
#Override
protected TCPClient doInBackground(String... params) {
Log.d(TAG, "In do in background");
try{
tcpClient = new TCPClient(mHandler,
COMMAND,
"192.168.1.1",
new TCPClient.MessageCallback() {
#Override
public void callbackMessageReceiver(String message) {
publishProgress(message);
}
});
}catch (NullPointerException e){
Log.d(TAG, "Caught null pointer exception");
e.printStackTrace();
}
tcpClient.run();
return null;
}
In this AsyncTask we are creating TCPClient object ( explained below ). In the TCPClient constructor we are passing Handler object for changing the UI, COMMAND - the String with the "shutdown -s" command for shutting down the computer, IP number - the servers ip number; Callback object - when we are getting servers response, the callback method 'messageCallbackReceiver' is starting 'publishProgress' method, which is publishing progress to 'onProgressUpdate' AsyncTask's method.
/**
* Overriden method from AsyncTask class. Here we're checking if server answered properly.
* #param values If "restart" message came, the client is stopped and computer should be restarted.
* Otherwise "wrong" message is sent and 'Error' message is shown in UI.
*/
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d(TAG, "In progress update, values: " + values.toString());
if(values[0].equals("shutdown")){
tcpClient.sendMessage(COMMAND);
tcpClient.stopClient();
mHandler.sendEmptyMessageDelayed(MainActivity.SHUTDOWN, 2000);
}else{
tcpClient.sendMessage("wrong");
mHandler.sendEmptyMessageDelayed(MainActivity.ERROR, 2000);
tcpClient.stopClient();
}
}
After receiving proper message, we are sending command, or if we received wrong message, we are sending message "wrong" and stopping client. After this we are being transferred to the 'onPostExecute' method:
#Override
protected void onPostExecute(TCPClient result){
super.onPostExecute(result);
Log.d(TAG, "In on post execute");
if(result != null && result.isRunning()){
result.stopClient();
}
mHandler.sendEmptyMessageDelayed(MainActivity.SENT, 4000);
}
}
So step by step:
->AsyncTask is creating TCPClient object.
->In TCPClient constructor we are passing Handler, Command, IP Number and Callback object.
->When TCPClient begins connection, it sends message "shutdown" to the server.
->When we are receiving message from server, the callback is passing it to 'onProgressUpdate'.
->If the received message ( response from server ) is equal to "shutdown", we are sending COMMAND to server.
->After sending it we are stopping client, which is transferring us to 'onPostExecute' method.
->Meanwhile, the handler is receiving empty messages with 'msg.what' integers defined in MainActivity, which are responsible for updating the GUI.
Example of how the widget UI is updated:
mHandler = new Handler(){
public void handleMessage(Message msg) {
switch(msg.what){
case SHUTDOWN:
Log.d(mTag, "In Handler's shutdown");
views = new RemoteViews(context.getPackageName(), R.layout.activity_main);
widget = new ComponentName(context, MainActivity.class);
awManager = AppWidgetManager.getInstance(context);
views.setTextViewText(R.id.state, "Shutting PC...");
awManager.updateAppWidget(widget,views);
break;
TCPClient
This class is responsible for maintaining the connection. I will explain it step by step:
In the first step we can see the objects passed from ShutdownAsyncTask and others. Additionally we can see the sendMessage and stopClient methods.
public class TCPClient {
private static final String TAG = "TCPClient" ;
private final Handler mHandler ;
private String ipNumber, incomingMessage, command;
BufferedReader in ;
PrintWriter out ;
private MessageCallback listener = null ;
private boolean mRun = false ;
/**
* TCPClient class constructor, which is created in AsyncTasks after the button click.
* #param mHandler Handler passed as an argument for updating the UI with sent messages
* #param command Command passed as an argument, e.g. "shutdown -r" for restarting computer
* #param ipNumber String retrieved from IpGetter class that is looking for ip number.
* #param listener Callback interface object
*/
public TCPClient(Handler mHandler, String command, String ipNumber, MessageCallback listener) {
this.listener = listener;
this.ipNumber = ipNumber;
this.command = command ;
this.mHandler = mHandler;
}
/**
* Public method for sending the message via OutputStream object.
* #param message Message passed as an argument and sent via OutputStream object.
*/
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
mHandler.sendEmptyMessageDelayed(MainActivity.SENDING, 1000);
Log.d(TAG, "Sent Message: " + message);
}
}
/**
* Public method for stopping the TCPClient object ( and finalizing it after that ) from AsyncTask
*/
public void stopClient(){
Log.d(TAG, "Client stopped!");
mRun = false;
}
The magic happens here - in 'run()' method. Here we are using 'try-catch' tools for handling exceptions ( server not enabled, ip not proper etc. ). As you can see below, we have infinite while() loop for listening to the incoming messages. We can simply stop it and finalize with 'stopClient()' method ( used in ShutdownAsyncTask's 'onProgressUpdate' method)
public void run() {
mRun = true;
try {
// Creating InetAddress object from ipNumber passed via constructor from IpGetter class.
InetAddress serverAddress = InetAddress.getByName(ipNumber);
Log.d(TAG, "Connecting...");
/**
* Sending empty message with static int value from MainActivity
* to update UI ( 'Connecting...' ).
*
* #see com.example.turnmeoff.MainActivity.CONNECTING
*/
mHandler.sendEmptyMessageDelayed(MainActivity.CONNECTING,1000);
/**
* Here the socket is created with hardcoded port.
* Also the port is given in IpGetter class.
*
* #see com.example.turnmeoff.IpGetter
*/
Socket socket = new Socket(serverAddress, 4444);
try {
// Create PrintWriter object for sending messages to server.
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//Create BufferedReader object for receiving messages from server.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d(TAG, "In/Out created");
//Sending message with command specified by AsyncTask
this.sendMessage(command);
//
mHandler.sendEmptyMessageDelayed(MainActivity.SENDING,2000);
//Listen for the incoming messages while mRun = true
while (mRun) {
incomingMessage = in.readLine();
if (incomingMessage != null && listener != null) {
/**
* Incoming message is passed to MessageCallback object.
* Next it is retrieved by AsyncTask and passed to onPublishProgress method.
*
*/
listener.callbackMessageReceiver(incomingMessage);
}
incomingMessage = null;
}
Log.d(TAG, "Received Message: " +incomingMessage);
} catch (Exception e) {
Log.d(TAG, "Error", e);
mHandler.sendEmptyMessageDelayed(MainActivity.ERROR, 2000);
} finally {
out.flush();
out.close();
in.close();
socket.close();
mHandler.sendEmptyMessageDelayed(MainActivity.SENT, 3000);
Log.d(TAG, "Socket Closed");
}
} catch (Exception e) {
Log.d(TAG, "Error", e);
mHandler.sendEmptyMessageDelayed(MainActivity.ERROR, 2000);
}
}
The last thing in the client is the Callback interface. We have it in the TCPClient class in the end:
/**
* Callback Interface for sending received messages to 'onPublishProgress' method in AsyncTask.
*
*/
public interface MessageCallback {
/**
* Method overriden in AsyncTask 'doInBackground' method while creating the TCPClient object.
* #param message Received message from server app.
*/
public void callbackMessageReceiver(String message);
}

smack message sent status

I am using smack and openfire for create chat app in android .
for message status I have no problem with delivered and displayed message in other
client (double check).
I will send a simple json message like bellow to sender:
{"delivery":timestapmp}
and parse it and double check messages with lower than timestamp that sent before.
the problem is about sent status (one check).
When i send message the server no response anything that message has sent .
is it possible in smack to send message with callback from server.
if possible and is it possible to send time server in callback response .
thanks .
private void acknowledgementFromServer(final Message message) throws StreamManagementException.StreamManagementNotEnabledException {
if (connection != null && connection.isSmEnabled()) {
connection.addStanzaIdAcknowledgedListener(message.getStanzaId(), new StanzaListener() {
#Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
MessageAsyncTask task = new MessageAsyncTask(packet.getStanzaId(), MSG_STATUS_SENT);
task.execute();
}
});
}
Hey you can do it like this.. call method every time you send message by passing that message as a parameter in above method
Note: Stream Management should be enabled for this to work, can be done like below:
DeliveryReceiptManager.setDefaultAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
ProviderManager.addExtensionProvider(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider());
ProviderManager.addExtensionProvider(DeliveryReceiptRequest.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceiptRequest.Provider());
According to my knowledge I have got up to this Inteface : ReceiptReceivedListener which is in smack 4.2
below is how I have implemented this :
private ReceiptReceivedListener receiptReceivedListener;
/**
* get DeliveryReceiptManager
*
* #return
*/
private DeliveryReceiptManager getDeliveryReceiptManager() {
if (deliveryReceiptManager == null && getConnection() != null) {
deliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(getConnection());
}
return deliveryReceiptManager;
}
add Listener
getDeliveryReceiptManager().addReceiptReceivedListener(receiptReceivedListener);
Received the call back
receiptReceivedListener = new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(Jid fromJid, Jid toJid, String receiptId, Stanza receipt) {
//TODO : on recieved status of message delivery
}
};
This will help you for sure
Below is the Interface for Smack 4.2 with full details :
/**
* Callback invoked when a new receipt got received.
* <p>
* {#code receiptId} correspondents to the message ID, which can be obtained with
* {#link org.jivesoftware.smack.packet.Stanza#getStanzaId()}.
* </p>
*
* #param fromJid the jid that send this receipt
* #param toJid the jid which received this receipt
* #param receiptId the message ID of the stanza(/packet) which has been received and this receipt is for
* #param receipt the receipt
*/
void onReceiptReceived(Jid fromJid, Jid toJid, String receiptId, Stanza receipt);

SignalR HTTP status 400 multiple clients

I'm running an application with SignalR 2.2.0 on server side and signalr-java-client (self compiled, last GitHub version) on Android as client.
Currently, there are 4 clients connected to my hub. From time to time, it happens, that all 4 clients simultaneously receive the HTTP status 400 with the message "The connection id is in the incorrect format" (the clients were connected before). I analyzed this multiple times and am not able to find any information/pattern when or why this happens.
The connecten is secured via JWT, the token is definitely valid. When retrieving a new token, the connection is stopped and started again. Apart from this, it is very unlikely that the error is device-related, because the error is thrown at all 4 clients the same time.
I know, this error can occur when the client's Identity changes, but an Identity change for 4 clients the same time seems very unlikely to me.
This is the server-code used for authentication (Deepak asked).
The following method gets called in my Startup.cs:
public static void ConfigureOAuth(IAppBuilder app, string audienceID, string sharedSecret)
{
byte[] secret = TextEncodings.Base64Url.Decode(sharedSecret);
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
Provider = new MyOAuthBearerAuthenticationProvider(),
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceID },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(Issuer, secret)
}
});
}
Here's the code of MyOAuthBearerAuthenticationProvider class:
class MyOAuthBearerAuthenticationProvider : OAuthBearerAuthenticationProvider
{
/// <summary>
/// Get's a JWT from querysting and puts it to context
/// </summary>
public override Task RequestToken(OAuthRequestTokenContext context)
{
if (context.Token == null)
{
string value = context.Request.Query.Get("auth_token");
if (!string.IsNullOrEmpty(value)) //token from queryString
{
context.Token = value;
}
}
return Task.FromResult<object>(null);
}
}
I have to retrieve the token from query string, because additionally to the java-client, a javascript client is used, which is not able to set headers.
Lastly, I secure my hub and some of it's methods with the Authorization attribute:
[Authorize(Roles = "MyExampleRole")]
This is the client-code for connection:
public boolean connect(String url, String token) {
if (connected) {
return true;
}
try {
this.hubConnection = new HubConnection(url, "auth_token=" + token, true, logger);
this.hubProxy = hubConnection.createHubProxy("MyHub");
this.hubProxy.subscribe(this.signalRMethodProvider);
this.hubConnection.stateChanged(stateChangedCallback);
SignalRFuture<Void> awaitConnection = this.hubConnection.start();
awaitConnection.get(10000, TimeUnit.MILLISECONDS);
return true;
}
catch (InterruptedException | TimeoutException | ExecutionException e) {
log.error("connect", e);
return false;
}
}
Does anybody have an Idea, how to fix this problem or where I may receive further information?
Thank you very much
-Lukas
seems fine...
possible alteration you can do is change
awaitConnection.get(10000, TimeUnit.MILLISECONDS);
to
awaitConnection.done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
Log.d(TAG, "Hub Connected");
}
}).onError(new ErrorCallback() {
#Override
public void onError(Throwable error) {
error.printStackTrace();
Log.d(TAG, "SignalRServiceHub Cancelled");
}
}).onCancelled(new Runnable() {
#Override
public void run() {
Log.d(TAG, "SignalRServiceHub Cancelled");
}
});

Identify Messages using Message API Android

I have probably a simple question but has me stumped. For my Android Wear application, I have two sensors working (step counter and heartrate).The wear app then sends these values back to the mobile application. I am sending them using the Message API. My stepcount sendMessage() and heartrate sendMessage() method look the same. Here is my heartrate sendMessage method.
private void sendMessageToHandheld(final String message) {
if (mGoogleApiClient == null)
return;
Log.d(LOG_TAG,"sending a message to handheld: "+message);
// use the api client to send the heartbeat value to our handheld
final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
final List<Node> nodes = result.getNodes();
if (nodes != null) {
for (int i=0; i<nodes.size(); i++) {
final Node node = nodes.get(i);
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), message, bytes);
}
}
}
});
}
Problem is I am only using one messageReceived method on the mobile. So I cant differentiate from the step value coming in or the heartrate value coming in.
#Override
public void onMessageReceived(MessageEvent messageEvent) {
super.onMessageReceived(messageEvent);
Log.d(LOG_TAG, "received a message from wear: " + messageEvent.getPath());
if (messageEvent.getPath().contains("HEARTBEAT")){
// save the new heartbeat value
currentValue = Integer.parseInt(messageEvent.getPath());
if(handler!=null) {
// if a handler is registered, send the value as new message
Log.d(LOG_TAG, "received a heartbeat message from wear: " + messageEvent.getPath());
handler.sendEmptyMessage(currentValue);
}
}
else {
// save the new steps value
currentStepValue = Integer.parseInt(messageEvent.getPath());
if (handler != null) {
// if a handler is registered, send the value as new message
Log.d(LOG_TAG, "received a step message from wear: " + messageEvent.getPath());
handler.sendEmptyMessage(currentStepValue);
}
}
I tried passing in a byte array into the Heartrate sendMessage() and other strings as flags so that I could tell the values apart but no luck. Anyone know what the best way to go about this would be?
Any help would be appreciated.
Cheers
It seems you are sending the data inside the path attribute. This is not the correct use of this parameter.
Let's take a look at the MessageApi.sendMessage(GoogleApiClient client, String nodeId, String path, byte[] data method.
What you want to do is use String path to provide identifier for your message, for example in your case it would be step_counter and heartbeat. This way you can identify it on the other side, when you receive the message.
The sensor data should go into data field. You can put it raw there, but a better way is to create a DataMap and then serialize it into byte[]. This way you can enrich the data later easily.

Android GCM: sendRegistrationIdToBackend syntax error on token void

I'm following the android GCM tutorial provided by google, and I get the following errors:
on the line:
private void sendRegistrationIdToBackend() {
// Your implementation here.
}
Syntax error on Token "Void", # expected.
Syntax error insert "enum Identifier" to complete EnumHeader.
Using, compiler 1.6
Thank you so much.
The entire function:
private void registerInBackground() {
new AsyncTask() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device
// will send upstream messages to a server that echo back the
// message using the 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP
* or CCS to send messages to your app. Not needed for this demo since the
* device sends upstream messages to a server that echoes back the message
* using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
}
}
It seems you forgot to close the registerInBackground() method.
Add } after }.execute(null, null, null);
Another way to look at it is that you put private void sendRegistrationIdToBackend() {} inside the registerInBackground() method, which is wrong.

Categories

Resources