I want to implement an android app which could communicate with a Server via internet. Since everytime the Android app connects to Server, there will be a connection established, and Android app will maintain this connection for the purpose of receiving msgs from Server. However, at the same time the Android app has to deal with User inputs, so these two tasks have to run concurrently that needs to realize by two Threads. I do not have experience about multi-threads programming. any suggestions? Thanks. leon.
The user interface is being handled by the main thread, so really you just have to set up one thread handling the networking (in fact, on 3.0 and on opening a socket connection from the main thread will throw an exception!).
Set up and maintain the connection to the server using an AsyncTask - this is a fairly easy way of doing multi threading. Take a look at this documentation: http://developer.android.com/resources/articles/painless-threading.html
Did you try to put the server interaction into a thread? This should be no problem at all
Thread thread = new Thread(this){
public void run() {
// do your server interaction
}
}
thread.start();
You may want to consider Google's Cloud To Device Messaging (C2DM). They manage to keep a connection open to a device for long periods and will push your server notifications to any android device. I believe its still currently in the 'labs' stage though.
Related
I have an Android application that has a chat client as one of its features. The chat client uses XMPP based on the Smack library for Android and running Openfire as XMPP server in the background. The connection is established using BOSH The whole XMPP connection handling is implemented as a service to run and listen in the background for incoming messages even if not activity of the app is in the foreground. So far, everything works perfectly fine.
The only problem seems to be the sleep mode. In the emulator (when set to "Stay Awake") or with the phone in use, the XMPP connections is holding and the app can send and receive messages. However, once the phone goes into sleep mode, the XMPP connection breaks down -- I can see it in the Admin Console of the Openfire server that the user is offline. Intuitively, I want to receive messages all the time like, e.g., WhatsApp.
Of course, I've searched online including Stackoverflow, but I couldn't get a definitive answer. Often the use case seems to be that a task has to be performed periodically, say, once every hour. But this doesn't seem to fir in case of a chat client. Since I assume this is a common use case -- after all, there a so many chat apps or apps with chat features out there -- these are my question:
How to I have to change / extend the app that I can receive chat message while the phone is sleeping?
I've stumbled upon WakeLock. Is this the way to go or are these not suitable for my use case?
Since Lollipop, there's also the JobScheduler API which itself uses WakeLock. Any better?
How does, for example, WhatsApp handles this case?
On a side note: I have problems with the sleep mode using the emulator for debugging. When I switch off "Stay Awake" in the emulator, the screen goes black after 1+ min and the XMPP connection breaks. But I somehow have no idea how to wake up / switch the emulator back on once it went black. Android Studio actually tells me at some point that the device or something is gone, and I have to restart the emulator again.
The exact way to resolve this issue is by using push notification.
It is the natural behavior of XMPP connection to get disconnected after the specified idle interval i.e when the device goes to sleep.
Coming to the case of WhatsApp, it also uses the same XMPP and maintains a server which acts as a wrapper class on the messages exchanged. This server checks the message status whether it is delivered or not. If not delivered, it sends a push notification, now at the device end in the push service when a message is received, it checks if the connection is active and is authenticated or not.
If not authenticated, it re-establishes the connection. In this way, the most chat apps manage this timeout exception.
Hope this helps :)
You don't need push notifications, you don't need WakeLocks. Instead simply
Whitelist your app from doze mode
Use a sticky (START_STICKY) background service
Use Smack's ServerPingWithAlarmManager
Act on CONNECTIVY_CHANGED intents send by Android, and use XMPPTCPConnection's instantShutdown() in that case.
I've been researching stackoverflow for days now, but can't seem to find a problem like mine.
I have an Raspberry Pi with a python socket server listening for incoming messages. Also I have a Android app which connects to it.
My idea was to create a "simple" music player on the raspberry pi with the use of the pygame module. You can see the Android app as the controller of the music player (Sonos like).
I already have a start, connecting the Android app with Raspberry pi is not the problem.
It's more how the communication between the two need to flow.
A few "solutions" I already thought about:
At the moment the Android app creates a socket object and connection in a new Thread then closes the Thread (so the Thread doesn't receive or sends messages, but the socket persists). When the user clicks a button (let's say to update the music list), it opens a new Thread then uses the already created socket object to send a command, gets a response and updates the UI then terminates the Thread again. And I do this for every action that needs to happen (play, pause, stop, etc.) With this method only the Android app has the right to ask for an action, because it's not constantly listening for server messages
So what if I would create a single thread which is in a constant loop sending a message and then getting a response: how do I interact with the loop from the main UI thread (like clicking a button). I thought about a synchronized List<String> MessageQueue where the main thread pushes a command and in the connection thread's while loops it checks if there are any messages that need to be send.
I made a little schema, how I had this in mind:
Schema (single thread with while loop):
single thread with while loop
Also the reason I chose sockets and not just a simple HTTP request is because later on want to update the UI so you can see real-time music playing (with the seconds updating and stuff like almost every musicplayer has, and who knows what more.
If you guys have any idea's, or know of any topics, example applications on how to create this then please share! If some things are not clear or are a little vague, feel free to ask/comment because I just started with asking on forums.
Example applications that use persistent socket connections with real-time communication are also welcome!
side question: would JSON be a good way to communicate between the 2 applications?
like this:
{
currentsong: "song1.mp3"
position: "1.30" // The current position the music is playing on the server
songlist: ["song1.mp3","song2.mp3","song4.mp3"]
...
}
I have a very basic design of my entire application, where several users with my app on there android devices commits data to the server (I have used REST web services(java) + postgresql as my server) through HTTP post request from the android application. I am successful in achieving this and app runs absolutely fine. Now i want to implement a scenario where any change(CRUD operations) on my db on server should create a notification on my users android device. How should i achieve this with my server design unchanged? I have looked into Google Cloud Messaging, but could figure out the server implementation.
For now i have implemented db triggers on postgresql and able to get control back into java code using Notify/Listen feature of postgresql. From here i need to connect to android device. How can this be achieved. Is Google Cloud Messaging the only way? I have not seen any insert/update statements in there server implementation. Could anyone please guide me on this?
either you can use GCM or implement a Socket at server end and open a socket connection from mobile but this approach may add some additional processing overhead because it will create a daemon thread to listen socket port from mobile device.
You should use native library (NotificationManager etc.), here you can find a great tutorial.
My Advice is for you to use GCM. GCM normally takes a maximum of 4kb, so you could have your own defined "commands". You could use them to determine the requests on both ends, ie on android app and the server end. A php script on the server would help you in this.
I am working on an app where by the android app sends messages to the server via POST and the server forwards the message to the appropriate user via GCM. In my case I have very many things to share so in that case I am using commands, for example if it is a new incoming message I send a GCM to the app with one variable as the command and the rest as the data. On the android app I use the command variable to determine what to do with the data.
Kindly avoid that socket advice, it will have your app drain the battery to sustain the open socket , besides you don't have to re-invent the wheel while Google servers already has it
I'm making a multi-client server chat application with Java.
Is there any way to not use multi-threads (1 thread for every client)?
Because my app runs on mobile, so multi-thread will make it too slow?
I guess you are misunderstanding the concept. A chat app intended to run on mobile device normally works like follows:
You will have a chat server, which is not in mobile application, hosted somewhere. This will communicate with client applications on different mobile devices.
In mobile client application, you will connect to chat server and process the data accordingly. This communication is generally done by socket connection.
Here every application acts individually so you do not need multi-thread in mobile application except any other functionality in your app need multi-threading. You can consider each application as different thread connecting on server socket.
For not mobile application some people use awesome Netty client-server (me too). Probably
some ideas of this server helps you to create right architecture :)
I am writing an android application to make server socket and receive messages from server
when I write the same application using Thread, it works pretty well but I am unable to access UI elements in Thread
whereas in case of services, startService method hangs on while(true){ socket.accept()}
You can read about threads and Android on the official documentation. Also, take a look at AsyncTask, that should help you a great lot.