I am trying to develop a sms sending and receiving test application in J2ME using the WMA API. I have separate threads for sending and receiving.
The Sending thread's run method -
public void run() {
try {
MessageConnection connection = (MessageConnection) Connector.open("sms://+" + number + ":1234");
BinaryMessage messageBody = (BinaryMessage) connection.newMessage(connection.BINARY_MESSAGE);
messageBody.setPayloadData(message.getBytes());
connection.send(messageBody);
connection.close();
} catch (IOException ex) {
}
}
The receiving thread's run method
public void run() {
try {
while (true) {
MessageConnection connection = (MessageConnection) Connector.open("sms://:1234");
BinaryMessage messageBody = (BinaryMessage) connection.receive();
message = new String(messageBody.getPayloadData());
number = messageBody.getAddress();
number = number.substring(6, 15);
App.setDisplay(number, message);
connection.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
I am initializing the receiving thread in the startApp() and initializing the sending thread when the send command is pressed. The problem I have is that if I use two Emulators, both sides can't send messages. One emulator can continuously send messages to the other but when the other emulator tries to send a message the message isn't received.
When a message is received by the emulator console shows -
[INFO] [sms ] ## javacall: SMS
sending...
when that line appears the emulator doesn't receive any messages. Where is the problem in my code?
PS: I saw that their is a way to use a listener to work around this problem with using a separate thread for receiving but I want to know where is the problem is in the above code?
Any help is really appreciated ^^
If you are running in emulator, use wma console available to send or receive messages. You can't do it from emulator to emulator. wma console is available at
utilities -> wma console
I found the problem... It's because SMS doesn't work in Netbeans above versions. It only works in Netbeans 6.1 ... Something is wrong with the emulator
Related
I would like to develop a simple android application that does that following
- Connects to server
- Sends "Hello" 10 times to the server every second for 30 minutes
I have the server connection part down. I have developed the server myself and have the message being saved to a text file. The application is on a timer like so
number = 1;
runnable = new Runnable() {
public void run() {
if (number > 5) {
System.exit(0);
}
showToastMessage();
number ++;
handler.postDelayed(this, 5000); // delay of 5 seconds
}
};
runnable.run();
The showToastMessage() method just shows a Toast message displaying the current value of number. I am currently using AsyncTask to connect to a server like so
protected Void doInBackground(Void...voids) {
try {
s= new Socket(IP, PORT);
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello");
dos.flush();
s.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
This doInBackground(Void...voids) method will connect me to my server and send the message "Hello". What I would like help with is how to send "Hello" each time runnable is run. If this is not a good approach please let me know. Should I avoid AsyncTask in this situation? Any help would be much appreciated!
I am currently trying to publish a command to a specific topic in the IBM IoT Foundation MQTT Broker using a Java web application. My application is already able to listen to device events and act on them, however publishing commands to the device is a problem. I know for sure that my device is listening to the proper topic for commands, so what could be the problem? More specifically, here is the command I call to publish to the topic (from my Java app):
publish("iot-2/cmd/" + MQTTUtil.getDefaultCmdId() + "/fmt/json", rawJSONCommand, false, 0);
System.out.println("Finished sending command!");
Where the "publish" method is defined as follows:
public void publish(String topic, String message, boolean retained, int qos) { // check if client is connected
if (isMqttConnected())
{
// create a new MqttMessage from the message string
MqttMessage mqttMsg = new MqttMessage(message.getBytes());
// set retained flag
mqttMsg.setRetained(retained);
// set quality of service
mqttMsg.setQos(qos);
try {
System.out.println("About to send!");
client.publish(topic, mqttMsg);
System.out.println("Finished sending!"); }
catch (MqttPersistenceException e)
{ e.printStackTrace(); }
catch (MqttException e)
{ e.printStackTrace(); } }
else {
System.out.println("Connection lost!"); connectionLost(null);
} }
All that happens is that I enter the method, I get "About to send!" printed on my console as the code specifies, and then the actual 'client.publish(topic, mqttMsg)' call blocks my program indefinitely.. Eventually, after blocking for a while, I get the following error:
org.eclipse.paho.client.mqttv3.internal.ClientState checkForActivity SEVERE: a:2uwqwc:<MY_APP_NAME>: Timed out as no write activity, keepAlive=60,000 lastOutboundActivity=1,452,646,209,624 lastInboundActivity=1,452,646,149,303 time=1,452,646,329,628 lastPing=0
Thanks for the help!
If you are publishing from an application, are you specifying the device type and device id?
myAppClient.publishCommand(deviceType, deviceId, "stop", data);
Refer to section in documentation about publishing commands to connected devices.
https://docs.internetofthings.ibmcloud.com/java/java_cli_app.html
I have two applications within my server, and use JMS via ActiveMQ to send messages between the two. My two apps are as follows
Web service - accepts HTTP requests, validates, then sends messages to be executed by the other application.
Exec App - accepts object messages, executes order, sends execution report back to the web service to present to the client.
My Exec app receives messages from the Web service within 200ms, no problems there. However when I send an exec report, the message can hang in the queue for over 10 seconds before being received by the web service. I am using the same code for both side's consumers so I am unsure what the cause would be.
Here is my message producer in the Exec App -
public void createAndSendExecReport(OrderExecutionReport theReport){
try {
logger.debug("Posting exec report: " +theReport.getOrderId());
this.excChannelMessageProducer.send(createMessage(theReport));
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
[there is a createMessage method which converts my POJO into an object message]
MessageListener listener = new MessageListener() {
#Override
public void onMessage(Message message) {
logger.debug("Incoming execution report");
try {
OrderExecutionReport report = (OrderExecutionReport)((ObjectMessage)message).getObject();
consumeExecutionReport(report);
} catch (Exception e) {
logger.error("Message handling failed. Caught: " + e);
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.error(sw.toString());
}
}
};
I get the log message "sending execution report"
Then nothing in the web service for up to 15 seconds later until finally I get "incoming ... "
What could be the cause of this?
Make sure you have enough MDBs running on the Exec App so they can handle the load.
My aplication is a multiplayer game in android, with a server running on google app engine and using GCM to conect the server with the player devices. i have registered the device in GCM and then i sent the registerId to the server to connect with the device. When i run the game sometimes it works fine but sometimes the device doesn¡t receive anything from GCM, the server still receive from the device. I have no idea what is happening :s
Here is where i register my device in the onCreate of the main class :
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
if (GCMRegistrar.isRegistered(this)) {
Log.d("info", GCMRegistrar.getRegistrationId(this));
}
regId = GCMRegistrar.getRegistrationId(this);
deviceId = getDeviceId();
if (regId.equals("")) {
GCMRegistrar.register(this, SENDER_ID);
Log.d("info", GCMRegistrar.getRegistrationId(this));
}
Then the first time i run the application on a phone i use this code to send the registationId to the server:
sendMessage("code=" + REGISTRATION_CODE +
"&deviceId=" + deviceId +
"®Id=" + regId +
"&phoneNumber=" + phoneNumber);
And here is the code in the server to send messages back to the device:
public void sendMessage(String regId, String text) {
Sender sender = new Sender(APIKey);
Message message = new Message.Builder().collapseKey("1").timeToLive(3).delayWhileIdle(true).addData("message", text).build();
try {
sender.send(message,regId,1);
} catch (IOException e) {
e.printStackTrace();//Manejar la excepcion
}
}
I can't understand why stop working, i'm in the middle of a game and stops working and then works again ...
I just solved it, the problem was the collapseKey here
Message message = new Message.Builder().collapseKey("1").timeToLive(3).delayWhileIdle(true).addData("message", text).build();
If you use the same collapseKey always sometimes you don't receive messages randomly so i try this and works finally works!!
Message message = new Message.Builder().collapseKey(""+((int) (Math.random () * (10000)))).timeToLive(3).delayWhileIdle(true).addData("message", text).build();
I have been going through several threads on here and didn't come across an answer to the issue I am running into.
My setup:
I have a Mac pc that I am using as a virtual serial port to communicate with my android Nexus S phone. Running the bluetooth chat app on the phone and using it as a client to talk to the virt comm I set up.
Initially I tried the bluetooth chat app with 2 android phones to confirm it works, which it does. I can send texts back and forth.
My Use case:
I have a device that reads RFid tags and sends the data to an android phone to collect the info.
I am using my PC to represent my device for now.
++++++++++++++++++
Ok to the problem,
I try to connect to the pc from my phone and initially I get a "connecting...." status bar update and after 15secs or so I get a toast message saying "I am connected to the pc" but immediately after I get "device lost connection" toast. Then the status bar goes to "not connected"
When I step through with the debugger, it seems to fail at the following portion of the bluetooth chat app. Specifically this line (bytes = mmInStream.read(buffer);)
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
When I look in logcat, the i/o exception is "software caused connection abort"
for the read() on inputstream.
Questions:
Does this have to do with my virtual port not setup right? I have the terminal up and waiting to receive input on /dev/tty.Nexus....
using the screen command # 9600 baud
Otherwise, I thought maybe the socket which the inputstream connects to is unavailable somehow. I printed that to log and it seems like it was not NULL. Every time I step through though it dies at the ConnectThread not in the ConnectedThread.
The following portion of code: specifically this line (mmSocket.connect();)
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
// Start the service over to restart listening mode
BluetoothChatService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
I wonder if the socket variable is losing scope due to multi-threading and the socket is being passed around?
Thanks
How you set up the virtual serial post on your Mac PC. Since you have tried to run the app on 2 phones and it's working, I think the problem is on the PC.
I have posted an entry about Android and Java Bluetooth here. Hope it will help.