i don't know how to read received messages in mobile device using J2ME midlet.Actually I have been sending the messages to other mobiles using SMS gateway.The sms gateway reply to the same mobile device,but i want to read the reply message on the device directly, not going to check the inbox.how to do this in j2me midlet using the PushRegistry concept.please give me the good idea or sample code for me...thanks in advance.
You should use the PushRegistry mechanism for this. In order to do so, you should mark in the .jad file that your application reacts to incoming SMS and also mark the SMS permission.
Put these properties to the JAD file:
MIDlet-Push-1: sms://:10214,hu.bute.daai.example.sms.MidletSMSPushDemo,*
MIDlet-Permissions: javax.microedition.io.PushRegistry, javax.microedition.io.Connector.sms, javax.wireless.messaging.sms.receive
Please note that you should use your own package and MIDlet name. In addition to that you should use the same port for SMS sending as it was defined in the JAD (10214 in the example).
After that when your MIDlet starts, you should call your SMS receiver code to get the SMS:
public class MidletJSMSProxy extends MIDlet {
public void startApp() {
initalize();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void initSMSReceive() {
new Thread() {
public void run() {
MessageConnection conn = null;
try {
String url = "sms://:10214";
MessageConnection conn = (MessageConnection) Connector.open(url);
TextMessage message = (TextMessage)conn.receive();
System.out.println("SMS: "+message.getAddress()+" - "+message.getPayloadText());
}
catch(Exception e){
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
}.start();
}
}
More info:
http://www.developer.nokia.com/Community/Wiki/How_to_launch_a_MIDlet_remotely_via_SMS_or_locally_via_an_Alarm_with_PushRegistry_in_Java_ME
Related
I am trying to create a service to autodiscover upnp devices in my local network, implementing it in a webapplication running on tomcat 7 and using 4thline Cling library.
I got this error
org.fourthline.cling.transport.RouterImpl handleStartFailure
SEVERE: Unable to initialize network router: org.fourthline.cling.transport.spi.InitializationException: Failed to set modified URLStreamHandlerFactory in this environment. Can't use bundled default client based on HTTPURLConnection, see manual.
In the cling's manual they say that Cling couldn't use the Java JDK's HTTPURLConnection for HTTP client operations. They suggest to configure network transport.
I didn't understand well how to do. Anyone had a similar problem?
Can you suggest me an example?
Thanks.
The code I am using is:
public class Example {
public static void startDiscovery() {
RegistryListener listener = new RegistryListener() {
public void remoteDeviceDiscoveryStarted(Registry registry,RemoteDevice device) {
String name = device.getDisplayString();
String url = device.getDetails().getBaseURL().toString();
String friendlyName = device.getDetails().getFriendlyName();
}
public void remoteDeviceDiscoveryFailed(Registry registry,RemoteDevice device, Exception ex) {
}
public void remoteDeviceAdded(Registry registry, RemoteDevice device) {
}
public void remoteDeviceUpdated(Registry registry,RemoteDevice device) {
}
public void remoteDeviceRemoved(Registry registry,RemoteDevice device) {
}
public void localDeviceAdded(Registry registry, LocalDevice device) {
}
public void localDeviceRemoved(Registry registry, LocalDevice device) {
}
public void beforeShutdown(Registry registry) {
}
public void afterShutdown() {
}
};
try{
UpnpService upnpService = new UpnpServiceImpl(listener);
upnpService.getControlPoint().search(new STAllHeader());
// wait 5 seconds for them to respond
Thread.sleep(5000);
upnpService.shutdown();
}catch(Exception e){
e.printStackTrace();
}
}
}
The following code connects to Twitch's IRC successfully and triggers the onConnect method which is where everything stops.
Because pIRCbot has verbose enabled I can see that it does send JOIN #twitchplayspokemon after connecting but the specification says that I should get an immediate response with the same text followed by a list of users (which would trigger the onJoin and onUserList methods) which doesn't happen.
I have also tried connecting to my channel and sending a message with
joinChannel("#[mychannelname]");
sendMessage("#[mychannelname]", "Hello World");
All this does is send two JOIN commands and doesn't ever join nor message appear in chat.
The tutorial/reference I'm using is http://help.twitch.tv/customer/portal/articles/1302780-twitch-irc
Other responses are also not being output. I am getting the MOTD but not seeing the "End of /MOTD command".
import org.jibble.pircbot.*;
public class MyBotMain extends PircBot {
public static void main(String[] args) throws Exception {
MyBotMain bot = new MyBotMain();
bot.setVerbose(true);
bot.setName("[myname]");
bot.setLogin("[myname]");
try {
bot.connect("irc.twitch.tv", 6667, "oauth:db4aai4mh474ikbgzzuh76fv67n"); // Not the key I'm using
} catch (NickAlreadyInUseException e) {
System.err.println("Nickname is currently in use");
} catch (IrcException e) {
System.err.println("Server did not accept connection");
e.printStackTrace();
}
}
#Override
protected void onConnect() {
System.out.println("Connected!");
joinChannel("#witchplayspokemon");
super.onConnect();
}
#Override
protected void onJoin(String channel, String sender, String login, String hostname) {
System.out.println(login + " joined channel " + channel);
super.onJoin(channel, sender, login, hostname);
}
#Override
protected void onUserList(String channel, User[] users) {
for (User user : users) {
System.out.println(user);
}
super.onUserList(channel, users);
}
}
Your code works perfectly fine, the only problem is that the channel you are trying to join is "witchplayspokemon" instead of "twitchplayspokemon" the onUserList(String channel, User[] users) is only giving me one user, But I have been having that problem recently on my own Bot So I am not yet sure on the cause.
I'm a newbie programmer looking for a way to implement a simple file transfer protocol on Android.
Problem:
Several Android phones need to connect to a server to receive/send a series of XML files saved in internal storage. The server needs to know which phone is requesting a connection so that it can save the files in the correct folder.
Possible solution/algorithm:
There are various tutorials/examples on how to send a file to a server, but none of them seem to implement some kind of "authentication".
Ideally I would like to implement the following (I'll use a metaphor):
Phone: Hello.
Server: Hi. Who are you and what do you want? [send/receive]
Phone A: I'm phone A and I would like to send files.
Server: How many files do you want to send, Phone A?
Phone A: 6 files, [+extra data like total size or whatever]
Server: Alright, you can begin the transfer.
Phone A: Transfers...
Server: I've succesfully received 6 files, have a good day. [stores the files in a PhoneA folder]
Phone A: Bye! [closes connection]
I realise this could very likely be made a lot more efficient, but I don't know where to begin...
Is it even possible to initiate a connection with a server and interact multiple times while waiting for responses?
Question :
Could anyone push me in the right direction somehow? Do I write my own protocol or can this be done with standard functionality? What are the best/easiest existing protocols for this kind of implementation?
I've found this article interesting but I don't see how it could be used for multiple files with authentication
Any help would be much appreciated!
This is easier than you think using old-school FTP, which I've used with success in collecting data from apps, and your server will surely support it.
Get a unique ID for each Android device using enter link description here. You get a 64-bit number (as a hex string) that is randomly generated on each device’s first boot. It's supposedly constant for the life of the device.
Import Apache Commons FTP and use the method describe here to create a directory name inside your working directory on the server with a name matching the unique id.
Use the same library to upload the files using FTP. You'll find many example of how to do this. It takes very minimal code.
Unlike your chat scenario, this is a very client-side solution, and phones you might not want to could upload files -- there's no blacklist -- but it's easy to implement.
For those interested in (terrible) code to perform various FTP functions, here's what worked for me.
It requires the apache commons ftp jar file which can be found on the internet.
//Button that starts it all
public void updateWorkordersList(View view) {
if (!CheckNetworkConnection.isOnline()) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
String connectionString = prefs
.getString("connection_string", null);
String userName = prefs.getString("FTPusername", null);
DownloadFilesTask task = new DownloadFilesTask(connectionString,
userName);
task.execute();
Fragment frg = null;
frg = getFragmentManager()
.findFragmentByTag("buttonsContainer");
final FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}
private class DownloadFilesTask extends AsyncTask<Void, Void, Boolean> {
private FTPClient mFtpClient = new FTPClient();
private FTPFile[] mFileArray;
private String _address;
private String _user;
private String _pass;
public DownloadFilesTask(String ip, String user) {
_address = ip;
_user = user;
}
#Override
protected Boolean doInBackground(Void... params) {
try {
mFtpClient.setConnectTimeout(10 * 1000);
mFtpClient.connect(InetAddress.getByName("insert server here"));
boolean status = mFtpClient.login("username", "password");
if (FTPReply.isPositiveCompletion(mFtpClient.getReplyCode())) {
mFtpClient.setFileType(FTP.ASCII_FILE_TYPE);
mFtpClient.enterLocalPassiveMode();
mFileArray = mFtpClient.listFiles();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Download All Files
if (FTPReply.isPositiveCompletion(mFtpClient.getReplyCode())) {
File directory = null;
directory = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getPath());
for (FTPFile file : mFileArray) {
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(
new FileOutputStream(directory + "/"
+ file.getName()));
mFtpClient.setFileType(FTP.BINARY_FILE_TYPE);
mFtpClient.retrieveFile(file.getName(), outputStream);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//Upload All Files
if (FTPReply.isPositiveCompletion(mFtpClient.getReplyCode())) {
File directory = null;
directory = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getPath() + "/srvReady");
for (File file : directory.listFiles()) {
try {
FileInputStream srcFileStream = new FileInputStream(directory + "/" + file.getName());
boolean status = mFtpClient.storeFile(_user + "/" + file.getName(),
srcFileStream);
srcFileStream.close();
if (status){
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
try {
mFtpClient.logout();
mFtpClient.disconnect();
} catch (Exception e) {
// TODO: handle exception
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Boolean result) {
}
}
I figure this could be of some use might someone ever come across a similar problem.
I'm a noob with vertx, but I have already created the JDBC connection manager using a java class where I can print data from the result set:
ConnectionManager cm=ConnectionManager.getInstance();
Connection conn = cm.getConnection();
try {
Statement stmt=conn.createStatement();
try {
ResultSet rs =
stmt.executeQuery("select username, password from users");
try {
if (rs.next()){
System.out.println(rs.getString(1));
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
conn.close();
}
Now I want to connect my vertx javascript app to this java class. I can't seem to get an idea where to start. I found a few sources from Google Groups, but none of them seem to shed some light:
Loading JDBC Drivers from JavaScript
https://groups.google.com/forum/?fromgroups#!topic/vertx/_oJQaeH07Sg
Executing Java from Javascript
https://groups.google.com/forum/#!msg/vertx/VyZj2yqqGTM/tvnTg4T55kMJ
I've also found a jdbc-persistor for Vert.x:
JDBC-persistor
https://github.com/timyates/mod-jdbc-persistor/
I'm still trying to understand how to use it with my app. I will post whatever information I can share after, but for now, can anyone help me with this (persistor or direct java communication)? Thanks.
AFAIK the only way to do it is using the event bus.
You put your Java code in a Verticle class (or in alternative create a module just for the goal). Something like this
public class JavaFromEverywhere extends Verticle {
#Override
public void start() throws Exception {
vertx.eventBus().registerHandler("invokeFromAnyLanguage", new Handler<Message<String>>(){
public void handle(Message<String> e) {
doSomething();
}
});
}
private void doSomething() {
// your database code here
}
}
Then in your javascript you should just write
vertx.eventBus.send("invokeFromAnyLanguage", "");
This is a simple scenario. If you want do more complex things like sending to your JS the String received from the DB you can extend BusModBase and send back data. Meanwhile in your JS you should register an handler to handle the reply
public class JavaReply extends BusModBase {
#Override
public void start() {
eb.registerHandler("invokeFromAnyLanguage", new Handler<Message<String>>(){
public void handle(Message<String> e) {
String something = doSomething();
e.reply(something);
}
});
}
private String doSomething() {
// your database code here
return "databaseResult";
}
}
and your JS code would be something like
eb.send("invokeFromAnyLanguage", "", function(javareply) {
// your answer in javareply
});
HTH, Regards
Carlo
I'm using Sun WTK to run a midlet that needs to send and optionally receive SMS. WMA console can be used to send and receive messages to the midlet but I'd like to do the same thing using my own application.
I have done some sniffing, and noticed that the messages are sent by UDP from the WMA console to the emulator.
After digging inside the jars in WTK I was able to figure out how to send and receive SMS. I had to include the jars kvem.jar and kenv.zip in the application classpath. Tested under Linux.
public static void main(String[] args) throws IOException, PhoneNumberNotAvailableException, InterruptedException {
System.setProperty("kvem.home", "/home/jassuncao/usr/WTK2.5.2");
WMAClient wmaClient = WMAClientFactory.newWMAClient(null, 4);
wmaClient.connect();
wmaClient.setMessageListener(new MessageListener() {
#Override
public void notifyIncomingMessage(WMAClient wmaclient) {
try {
System.out.println("Message received:"+wmaclient.receive());
} catch (IOException e) {
e.printStackTrace();
}
}
});
System.out.println("This number "+wmaClient.getPhoneNumber());
String[] receivers = wmaClient.getKnownReceivers();
for (String receiver : receivers) {
System.out.println("Sending SMS to "+receiver);
Message msg = new Message("Hello world!!");
msg.setFromAddress("sms://"+wmaClient.getPhoneNumber());
msg.setToAddress("sms://"+receiver);
//It seems the ports must be set AFTER the address to work
msg.setToPort(50000);
msg.setFromPort(50000);
wmaClient.send(msg);
}
System.in.read();
wmaClient.unregisterFromServer();
}