Android 3g connection delay - java

I'll appreciate your help with the following:
Question:
I'm looking to rush the 3g connection and make it connect immediately.
Explanation:
I built an app (for Android), using HttpClient for connecting to my server, and Amazon's AWS API to connect to various Amazon services.
I noticed that occasionally, the connection establishment in 3g takes a lot of time, and it actually seems that Android just waits a while before sending the GET/POST/whatever request, and not even trying until then.
Few Clarifications:
the 3g connection IS working (good signal) and the problem is with 3g ONLY.
when trying to connect to the internet using a browser (e.g Boat Browser), the connection seems to "wake up" and those green&orange arrows at the status bar start lighting again. And..the browser works. Sometimes my request get "awakened" then as well.
My requests DO work, but usually it takes a while (at least 1 minute) until they actually initiate.
I can put some code if needed, but it looks like it isn't related to what I do, it's just how Android works (maybe it's waiting for many requests before initiating 3g connection?), and that some apps (like Boat Browser) force the connection to send their request, or just refresh the 3g connection maybe.
Thank you so much

Ok I found enough information to clear this up!
The best thing to do with AsyncTasks as connection threads is to avoid them apparently,
And use Google Volley instead.
Please look at this link to understand the nuances concerning AsyncTasks:
http://www.jayway.com/2012/11/28/is-androids-asynctask-executing-tasks-serially-or-concurrently/
(I found this link in a separate question but I can't find it, sorry).
And look at this link to understand what is Google Volley and how it's easier to implement a multi-threaded connection with it:
https://developers.google.com/events/io/sessions/325304728
So..To answer the question:
1. On some/most cases, your AsyncTasks will NOT run concurrently.
2. In order to "force" a multi-threaded connection, use Volley (can be configured to run serially btw) or read the link above concerning AsyncTask to "enable" it.

Related

Android HttpURLConnection connection refused after few minutes in service when ui is not visible

I am working on small chat application which is working fine when the app is visible to user. A service class which get and send data using post every 5 second when aap is visible to user and works fine. But when app.is closed and service works in background for few minutes fine. After few minutes i.e. apprx 3 minutes it get conmection refused error and never fetch data from server until.the app is again visible to user. I cant find any solution. please help.me
I uses HttpURLConnection for posting data, and a Thread and timer for regular posting.
Android suspend applications when they get into background, to make resources available for the foreground application. If you need to sync your data on the background you should use a Background Service or SyncAdapter.
Take a look at Best Practices for Background Jobs and Transferring Data Using Sync Adapters
Some tips:
Do not use manual timed HTTP requests for chats messages, its a very bad practice,
But, if you want to keep this, use some new http request library like "Volley" or "OkHttp" (this is my favorite),
If you want more professional and highly "best practice" stuff, use the Google's Firebase Cloud Messaging for chats apps, its use native google services for send messages to others apps, highly recommended.
Connection Refused can be your client (service) sending wrong data/values, wrong URL, wrong ports and wrong query, please post a piece of your code.

How to simulate different server responses, including offline?

An app I am working on relies on connecting to a private, remote server to login via an API.
The other day, I got an ANR message and I think it was due to the server being offline (its a Windows Server that was being updated).
In my app, I am using the following code:
new ReadJSONFeedTask().execute(url).get();
Which turns an AsyncTask into a synchronous task (I believe!)
And because the server was offline, I think the app got hung up, causing the ANR (it's my only lead at the moment, and all seems to make sense, despite the code above is inside a Service class, which shouldn't cause an ANR, should it?)
So, I want to try an simulate the server being offline. I tried replacing the URL with one that simply doesn't work, by removing some letters from the hostname, but that only triggered an "UnknownHostException".
Is there any way to achieve this kind of simulation? I know there are tools for browsers to simulate low bandwidth etc, but have no idea what could be done when my app is running on Android and is trying to connect to a remote server that I can't really reboot at will.

Less response Time from webserver

I had developed an app in android that take some data from a database stored on a web server and draw a GUI according to data captured.The problem is that when i run app on localhost using (WAMP) it creates GUI in 2 seconds but when i connect it to the webserver it takes almost 7 to 10 minutes.I am astonished what could be the possible reason behind this.
I had not used any ASync class in my code.I had used httpclient.execute stuff to connect to web server and JSON pasring.I hope you understand.Please tell me what could be the reason behind less response time.
first thing is whats the speed of your internet ? if your connection is slow that could be the reason. and other thing is you might be doing all gui processing on client via request only. my suggtion is have screens ready and fill data via things like json/REST stuff. for others i can only tell you once you show some code.

Play framework longpolling in online game

I'm working on a browser game with the play framework, and I definitely need longpolling, but I don't quite understand how to use it. WebSockets would be perfect for this, but it's not supported by that many browsers yet.
Here's what I want to do: When the user logs in, and navigates to the play game controller, I want to start a connection, and keep it open. I want to do this for all users that are online, so I can show a list of them on the site, so they can play with each other. I've looked at the documentation, but I don't understand how I could implement it in my case. Because there simply isn't anything I want to calculate (in the example they're generating a pdf) I just want the connection to stay open.
What I'm also wondering is, how I should keep track of all these open connections? Right now, I just have an online column in my users table in the database, which I update. SO everytime someone connects I have to update the database. Are there better ways to do this, or is this fine?
And lastly, assuming all of the above works. When player A, selects player B to play with: how do I notify player B of this? Do I just send some JSON code, and change the page with javascript, on player B's side, or do I send him to a totally different page? I'm not sure how to communicate when the two connections are established and the game has started.
Firstly, I think you need to appreciate the difference between Websockets and Long Polling.
Websockets creates a connection and keeps it open until the browser terminates the session, via some javascript or the user moving on from the page. This would give you the desired nature of what you are requesting. Looking at the Chat example in the Play download will show you how an entire Chat application is handled using Websockets.
Further to Pere's answer regarding Play's statelessness. The Play creators have suggested that a single Websocket connection, regardless of how long it is open for and how many requests are sent back and forther, is considered to be a single transaction. Therefore, saving to the database in between each Websocket request is not needed (again, you can see that nothing is saved in the Chat example). Using this method, you would be expected to save the details when the Websocket is finally closed, or indeed all Websockets, depending on your use-case.
Long Polling on the other hand opens a connection to the server, and the server simply waits until there is something to send back to the client. If you need to push any data to the server, you would do this as a separate AJAX request, so you would effectively have two requests open at once. You don't necessarily know when a user logs off, unless you send a request just as they leave the page, to let the server know they have gone, but this is not always successful. Long Polling can work, but it is not as neat a solution as Websockets, but as you say, this is not widely supported yet.
My suggestion would be to study the Chat example (as it has a Long Polling and Websockets version). This will be the most effective way to get up and running with your requirements.
As for your final query regarding how to notify the other player. In Long Polling, you would simply respond to the suspended request with some JSON. With websockets, you would send an event back to the client. Again, both approaches can be pretty clearly figured out from the Chat example.
I have also written a Blog post on Websockets, which may help you understand this process a little better.
On the Websocket part, as you can see here (1st answer) the support is not so bad, and you have a Javascript fallback if there is some problem with the browser. This would simplify your scenario, as long polling may be more complicated to manage.
On the issue of keeping track, as Play is stateless you have to store the flag in the database and remove it when they close the connection. Otherwise you are breaking the statelessness.
About the notification, you have to send some message to B, but don't move them to another page as it may be confusing and cause bad user experience. Use Json to pop some message (in a div) alerting them of the game starting or the request to play.
I'm not using the "play" framework.
But I've been lately researching and tinkering with http-based long polling. Websockets, if available, is much more appropriate for realtime messages!
As for long-polling, I found that using a "cargo truck" analogy helped me reason about long-polling quite effectively. Here's a little note I wrote on the subject:
http://dvb.omino.com/blog/2011/http-comet-realtime-messages/
Perhaps you or future greppers may find it useful.
You might also want to take a look at the Juggernaut project which is based on node.js and Redis and gives you a "realtime connection between your servers and your client browsers". When using a Java Redis client like Jedis, you should easily be able to integrate the whole thing with the Play framework!

How do I test the availability of the internet in Java?

I don't want to tell the hard way that the internet is unavailable when I catch an exception from url.openStream().
Is there a simple way to tell if the computer is connected to the internet in Java?
In this scenario, "connected to the internet" means being able to download data from a specific url.
If I try to download from it and it is not available, then the program hangs for a bit. I dont want that hanging. Therefore, i need a fast way of querying whether the website is available or not.
The problem you are trying to avoid is waiting for for your http connection to determine that the URL you are trying to access is really unavailable. In order to achieve this you need to stop using url.openStream() which is a shortcut for openConnection().getInputStream() and get some finer control over your connection.
URLConnection conn = url.openConnection();
conn.setConnectTimeout(timeoutMs);
conn.setReadTimeout(timeoutMs);
in = conn.getInputStream();
This code will allow you to timeout the connection attempt if either the connection or the read exceeds the time you provide in the timeoutMs paramater.
Use
Process p1 = java.lang.Runtime.getRuntime().exec("ping www.google.com");
System.out.println(p1.waitFor());
// return code for p1 will be 0 if internet is connected, else it will be 1
There is no such thing as "Internet availability".
Imagine that your HTTP request go through a transparent HTTP proxy, you are trying to access a blacklisted site and you get a HTTP response from the proxy server telling you about access denied. Is Internet available in this scenario or not?
I think you shall be more specific about your problem.
You might be able to tell if a compouter is connected to a network but even if it is there's no guarantee the networking is working or that it's connected to the internet.
This is one of those "suck it and see" problems.
What's wrong with trying to connect? And why are you concerned whether or not they're connected to the internet?
If the criteria is whether you can access a given web server the only way to find out, is to access that web server.
You can, however, do it in a background thread at start up so the application is not delayed by it. Then the "yes/no" answer is available when the actual downloading is desired. Put a message in the status line so the user knows what is going on and is not suprised about uninitiated "connect to network" if s/he is not connected when your program is started.
I don't know much about the low level HTTP plumbing available in Java, but you could always issue an http HEAD request for the url in advance. This causes the server to send back only the headers and not the data. With a 1-3 second timeout, you should be able to avoid any lengthy delays.
If you program is hanging while waiting to download then you are probably using the GUI thread to do the download. If you use a background thread, your program won't hang even if it take a long time to timeout/download.
You could send an ICMP message to a very well known host...
You can check for a NTP server if your firewall does not forbids.
Any way I think the best option is to try to open an URL as you try to avoid, because is the service most commonly to be opened.
You can check for one or two dynamic URL that change constantly. For instace, some web that shows time. For instance this one i found googleing. More than one because the sites can be down ;-)

Categories