Problem using J2ME WMA to send/receive SMS - java-me

I'm using WMADemo of the JavaME SDK 3.0 and it's working fine in simulator.
When I install the application in a mobile device it doesn't work. I tried both port 0 (default SMS) and 50000 (listener) with no success. No exception was thrown.

This is an example that works for me
try {
String dest = "sms://" + yourRecipientNumberString;
MessageConnection mConn = (MessageConnection) Connector.open(dest);
TextMessage sms = (TextMessage) mConn.newMessage(MessageConnection.TEXT_MESSAGE);
sms.setPayloadText(msgText);
mConn.send(sms);
mConn.close();
sent = true;
} catch (IOException ioe) {
ioe.printStackTrace();
sent = false;
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
sent = false;
} catch (SecurityException se) {
se.printStackTrace();
sent = false;
}

Related

Device not accepting incoming connection in J2Me Bluetooth?

I am trying to do communication between a mobile application (using J2ME and JSR82) and Desktop application (in C# using InTheHand Library).
I am using RFComm protocol with UUID: 00000003-0000-1000-8000-00805f9b34fb.
I have manually specified uuid on both devices. I have mobile application to wait for incoming connections, while desktop application sends data to it.
But, my mobile application just does not listen to incoming connection. It just hangs at the message: "Waiting for incoming connection..."
J2ME code in Mobile Application:
public void startApp() {
if (midletPaused) {
resumeMIDlet();
} else {
initialize();
startMIDlet();
form.append("UID: "+ uuid.toString() +"\n");
//set the device discoverable
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
form.append("Device Address: "+localDevice.getBluetoothAddress()+"\n");
form.append("Name: "+ localDevice.getFriendlyName()+"\n");
}
catch (BluetoothStateException exception) {
form.append(exception.toString()+"\n");
}
//setup a server socket
StreamConnectionNotifier streamConnectionNotifier = null;
try {
String url = "btspp://localhost:000300001000800000805f9b34fb;name=rfcommtest;authorize=true";
//form.append(url);
streamConnectionNotifier = (StreamConnectionNotifier)Connector.open(url);
if (streamConnectionNotifier == null) {
form.append("Error: streamConnectionNotifier is null\n");
return;
}
}
catch (Exception exception) {
form.append(exception.toString()+"\n");
}
//wait for an incoming connection
StreamConnection streamConnection = null;
try {
form.append("Waiting for incoming connection...\n");
streamConnection = streamConnectionNotifier.acceptAndOpen();
if (streamConnection == null) {
form.append("Error: streamConnection is null\n");
} else {
form.append("Connection received.\n");
}
}
catch (Exception exception) {
form.append(exception.toString()+"\n");
}
//write hello and then exit
try {
OutputStream out = streamConnection.openOutputStream();
form.append("Stream \n");
String s = "hello";
out.write(s.getBytes());
out.flush();
streamConnection.close();
form.append("Text Written to stream\n");
}
catch (Exception exception) {
form.append(exception.toString()+"\n");
}
}
midletPaused = false;
}
C# Code in Desktop App:
cli = new BluetoothClient();
BluetoothEndPoint ep1 = new BluetoothEndPoint(info[listBox1.SelectedIndex].DeviceAddress, BluetoothService.RFCommProtocol);
cli.Connect(ep1);
Stream stream = cli.GetStream();
StreamWriter sw = new StreamWriter(stream);
sw.WriteLine("Tesing");
sw.WriteLine("testing");
sw.Flush();
sw.Close();
stream.Close();
Please help me out on this.

Download Images in loop java me

In my application we have to download around 10 Images from server and display it in mobile. How can I do this? Can I use same HttpConnection for full download? Is any other way for download?
You can do with this simple loop (Supposing imageList is a List with the url of the images).
HttpConnection = null;
Image image = null;
for (int i = 0; i < imageList.getSize(); i++) {
try{
String urlImage = imageList.get(i);
hc = (HttpConnection) Connector.open(urlImage);
image = Image.createImage(hc.openInputStream()));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
hc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You can try following method in a loop for downloading images from server.
private void downloadImage ( String URL )
{
try
{
System.out.println("URL FOR POST_DATA : "+URL);
// Open up a http connection with the Web server for both send and receive operations
httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);
// Set the request method to POST
httpConnection.setRequestMethod(HttpConnection.POST);
// Set the request headers
httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);
if(eventName==null || eventName.equals(""))
eventName="default";
httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
// all the headers are sending now and connection chanel is establising
dis = httpConnection.openDataInputStream();
int ch = 0;
ByteArrayOutputStream bytearray = new ByteArrayOutputStream(250000);
while((ch = dis.read()) != -1)
bytearray.write(ch);
// fileByte contains whole file in bytes
byte fileByte[] = bytearray.toByteArray();
fileSize = fileByte.length;
System.out.println("Got file size : "+fileSize);
if(bytearray!=null) bytearray.close();
midlet.getLastPostedImageResponse(fileByte);
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.out.println("IOException occured during getting last image data : "+ioe.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Eeception occurred during getting last image data : "+e.getMessage());
}
finally
{
System.out.println("Calling close from Last image posted Action");
close();
}

How to post data to server in J2ME? Getting response from server Invalid API Key

I am posting some data to server but i am getting {"status":false,"error":"Invalid API Key."} response from server. My API Key is correct but where is the problem i don't know. Please friends help me. I tried lot but i did not find solution. I have used following code for posting data to server.
public void tryingOne(String dtl){
HttpConnection httpConn = null;
InputStream is = null;
OutputStream os = null;
String url="http://api.geanly.in/ma/index?API-Key="+apikey;
String details = "&orderInfo={\"booking\":{\"restaurantinfo\":{\"id\":\"5722\"},\"referrer\":{\"id\": \"9448476530\" }, \"bookingdetails\":{\"instructions\":\"Make the stuff spicy\",\"bookingtime\": \"2011-11-09 12:12 pm\", \"num_guests\": \"5\"}, \"customerinfo\":{\"name\":\"Vinodh SS\", \"mobile\":\"9345245530\", \"email\": \"vind#gmail.com\", \"landline\":{ \"number\":\"0908998393\",\"ext\":\"456\"}}}}";
try {
System.out.println("url####"+url);
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream outStream = new DataOutputStream(httpConn.openDataOutputStream());
outStream.write(details.getBytes(),0,details.length());
outStream.flush();
outStream.close();
//Reading Resp. from server
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1) {
sb.append((char) chr);
}
System.out.println("Response from srvr " + sb.toString());
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (httpConn != null) {
try {
httpConn.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Please help me friends...
Thanks
you need to trim the variable "apikey".
I was getting same problem when connecting with Picasa Server.
For sending data using HttpConnection use the class in this tutorial. It also gets the response from the server.

solution an error in receive sms

When send sms from a device to another sometime it received in both devices.
I don't find any error in source code.
Please help me.
NOTE:
this is send source code:
try {
String addr = "sms://" + txt_number.getString()+":1234";
MessageConnection conn = (MessageConnection) Connector.open(addr);
TextMessage msg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(txtSMS.getString());
conn.send(msg);
conn.close();
} catch (IOException ex) { ex.printStackTrace(); }
<blink>and this is receive opretion .this opration support by a thread <blink>
public void run() {
String addr="sms://:1234";
Message msg=null;
try {
conn = (MessageConnection) Connector.open(addr);
while(true)
{
msg=conn.receive();
String mSenderAddress = msg.getAddress();
if (msg instanceof TextMessage) {
String msgTReceived = ((TextMessage)msg).getPayloadText();
Analize_TEXT_message(mSenderAddress,msgTReceived);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
Remove the port number when sending the SMS.
String addr = "sms://" + txt_number.getString()+":1234";
should be
String addr = "sms://" + txt_number.getString()+1234;
port number should be without any quotes.

How do I send a message to a bluetooth device?

Using the bluetooth API in j2me, I want to send a message to another mobile phone. I have been able to discover devices and services on the corresponding devices. I have also been able to connect to the services however when I try to send a message from the server to the client. The message is written but the client does not seem to receive it ..
public void startServer() throws IOException {
UUID uuid = new UUID("1101", false);
//Create the service url
String connectionString = "btspp://localhost:" + uuid + ";name=xyz";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection = streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: " + dev.getBluetoothAddress());
System.out.println("Remote device name: " + dev.getFriendlyName(true));
Survey.setTitle(dev.getFriendlyName(true));
//read string from spp client
try {
DataInputStream in = connection.openDataInputStream();
OutputStream writer=connection.openDataOutputStream();
String str="";
TextField textfield;
for (int i=0;i<questions.size();i++){
textfield = (TextField) questions.elementAt(i);
str += formatSurvey(textfield,i)+"&";
}
writer.write(str.getBytes(), 0, str.getBytes().length);
writer.flush();
System.out.println("Written to client "+str);
System.out.println("Reading "+in.readUTF());
try {
displaySurveyresults(str);
}
catch(Exception e){
System.out.println(e.getMessage());
}
streamConnNotifier.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
switchDisplayable(null , getList1());
list1.append(servRecord.toString(), null);
System.out.println("Service discovered..."+servRecord.toString());
for (int i=0;i<servRecord.length;i++){
try {
System.out.println("Test1");
//StreamConnection con = (StreamConnection) Connector.open(servRecord[i].getConnectionURL(0 , false));
String connURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
// Open connection
StreamConnection con = (StreamConnection) Connector.open(connURL);
System.out.println("Test2");
DataInputStream in = con.openDataInputStream();
System.out.println("Test3"+in.readUTF());
//con.openDataOutputStream().write(142);
System.out.println("Test4 "+in.available());
byte[] bte=new byte[in.available()];
System.out.println("Test5 "+bte.length);
in.read(bte);
System.out.println("Test6");
for (int l=0;l<bte.length;l++){
System.out.println(bte[i]);
System.out.println("Test7");
stringItem.setText(stringItem.getText()+1 + bte[i]);
}
OutputStream outStream=con.openOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outStream);
writer.write("Vimal");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
have I erred somewhere bcause these are codes from the Net?
Try replacing new UUID("1101", false); with new UUID(0x1101);.

Resources