I'm getting to a point in the development of an Android app where I've reached a stumbling block: how to create, manage, and connect to a Socket in Android.
My app needs to keep a persistent TCP connection to the server in order to exchange JSON formatted strings back and forth. After reading up on the subject, I've determined the best way forward is to create a Service when the app starts up (by extending the Application class and starting the Service in onCreate()), then read from/write to the Socket as needed. But how do I do that?
I obviously know how to create a Service and how to create and work with a Socket. But I don't know the best way to interact with one in an Android environment. Should I create an AsyncTask whenever I want to write data? Should I use Intents? Any help on the subject would be wonderful. And if my question isn't clear, I'll be more than happy to clarify anything.
Within the service, you can simply listen as you would in a regular Java application. This means you can safely wait for IO as you normally would.
You will have to use Intent when you wish to notify your activities about new data arrival using sendBroadcast and receiving it to your activities by either registering a BroadcastReceiver using registerReceiver or modifying your manifest file.
This is a good tutorial that may help you with broadcasting for Service <-> Activity communication.
Apparently I was thinking about this problem incorrectly. What I need is to implement a "Bound Service", which will give my Activity an interface to interact with in order to send and receive messages.
Here's a link to the tutorial I found which gives an excellent overview of how to do this.
Related
I'm Working in an Android project that generates data and then it registers that connecting to a WebService, the data can be created even if the user doesn't have an active internet connection in that moment. So, I want a way to run a function that calls the webservice and pass the data when a valid internet connection is detected, all in background. I have read about SyncAdapter and JobScheduler, but I'm very confused about these options because I'm very new in Android development, any help or suggestion to decide which option is better to accomplish this would be very appreciated, thanks in after hand.
You should use broadcast receiver. By that way you can check internet connection in a broadcast receiver and then do some stuff in background.
this is a good tut to how use it.
I have built a simple application that accepts data entered by the user and saves it to the local sqlite database. If wifi connection is available it will transmit the data to a REST service hosted on a remote server.
I have done the above part and it is working pretty fine. If WIFI is not available it will just move on and will expect new data from the user.
When the wifi becomes available, i have registered a broadcast receiver which will hit my database and get the values stored and send them to the remote server.
I would like to know, while the broadcast receiver is trying to query my database, if the user is entering data at the same time and it is being saved in the same database, will it fire a SQLException.
As i recall, only one service can access the SQL instance at a time. If it will pose a problem what shall i do to overcome it. I have looked at ContentProviders, would that be the solution?
I am fairly new to android. Please advice.
You may want to take a look at this.
What are the best practices for SQLite on Android?
For me, I would suggest to always create a ContentProvider together with DatabaseHelper when you need Database, no matter you need to provide your data to external application or not. It is actually not difficult to do, the best reference I used to build my ContentProvider is DeskClock, the official app from Android.
Edit:
As a side note, you should consider to create a IntentService to be called by your boardcast receiver to do the work, as broadcast receiver should not be used for long running task, like sending things to server.
BroadcastReceiver#onReceive
When it runs on the main thread you should never perform long-running
operations in it (there is a timeout of 10 seconds that the system
allows before considering the receiver to be blocked and a candidate
to be killed).
basically i need a constant socket connected to a server that can be used in multiple activities. at this stage im trying to create and connect the socket on a login screen, where then a new activity starts, sets the input/output streams and then handles the data
im having alot of trouble trying to get the socket to persist in multiple activities. i have read into it and there is a lot of conflicting posts saying that services are better and a singleton is better. nonetheless i choose to try and implement a service. except i cant get it started.
How to keep the android client connected to the server even on activity changes and send data to server?
i first tried to implement the code in the above link but it seems to depend on custom written code called TCPClient. not knowing the internals i moved onto the link below
Android service for TCP Sockets
needless to say ive gotten nowhere in understanding and following the Android resource hasnt really helped. according to the guy who posted the first link his code works, i just dont know whats inside the TCPClient class.
im trying to use the code from the second link, and adapt it for my app, but hasnt worked so far. right now im poking around in the dark.
ultimately, id like an explanation on how to get a tcp socket service started, or a better way to attempt this.
TIA
i'm trying to build an application that every given time, will connect to a remote server and get JSON object from it.
as i searched the web for answer i wasn't able to realize exactly how to setup a service and run it as long as the application is running.
i want my main.xml screen have some kind of TextView which will update from the service.
couldn't found anywhere how to build a service which update a TextView when needed..
i'm looking for a simple example - as for i'm newbie to android development.
What you should look for -- perhaps instead of a service in this instance -- is an AsyncTask. This is what you use when you need to update the UI from the background and not hang around too long on the main thread. Here's one AsyncTask tutorial, and here's what the Android SDK docs have to say about it.
If you need to do things like download JSON every so often from a server, a Service might be a good solution. To communicate back and forth between a Service and an Activity you will use a Messenger and Handler example. You can find an example of how to use the messenger / handler pattern for services and activities in the API demos included with the SDK (here). this SO thread is also relevant.
If you need to keep your service running every so often, you'll want to look at using an AlarmManager to grab the data, store it somewhere, and then refresh the display in the Activity (perhaps through a database in your app). But basically, if you need to quickly download some stuff and update an Activity, use an AsyncTask, if you need something longer term, bind a service and then communicate back and forth between it and the Activity using a Messenger / Handler pair (or AIDL, but that's more complicated..)
You might be able to use a bound service to achieve it. http://developer.android.com/guide/topics/fundamentals/bound-services.html
I have an android app that listens for json commands over a socket. I am wondering how I can implement this as a background service. The service would receive the commands and depending on which commands they are, notify the user, or update data within the main program. Some code examples would be great if anyone has them. I've got an example of how to build a background service however it uses timers. I'd like for socket to always be listening.
In this case you would use a Service which responds to events sent over the socket.
The service should be started by the activity (could also be started on boot if needed).
For code example I would recommend commonwares projects on GitHub. There are many great examples using Services there.
(There is also a service example in an ongoing app I have here.)