AsyncTask's get() method's behavior changed with different API levels - android

My app's targetSdkVersion is 11. I need to upgrade it to 14 or upper. Unfortunately my current code heavily depends on codes like this.
int timeout = 5000;
return new HttpMnagerAsync().execute().get(timeout, TimeUnit.MILLISECONDS);
In targetSdkVersion 11:
This code execute the method HttpMnagerAsync()'s doInBackground() immediately and wait for 5 seconds for complete the execution and return the results. If failed to finish in 5 seconds a timeout exception returns. (This is the expectation)
When changed to targetSdkVersion 14:
This code waits 5 seconds doing nothing, and it returned timeout exception, and then it hits the HttpMnagerAsync()'s doInBackground() method.
I need to upgrade the targetSdkVersion to 14.
any explanation is appreciated to overcode this issue.

Calling get() will not make Asynctask asynchronous, get() waits for the result blocking the ui thread. Remove get() and use execute like for example:
new HttpMnagerAsync().execute();
Then, you can set your timeout in Http client, for example:
try
{
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 6000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
}
catch (ConnectTimeoutException e)
{
//Here Connection TimeOut excepion
Toast.makeText(xyz.this, "Your connection timedout", 11000).show();
}

Related

Android how to show toast on Connection TimeOUT

I am using below code to check the connection time out in Android. On top of this how can I show Toast if connection actually times out? Any suggestion?
/*Client timeout*/
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000; //3Seconds
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000; //5Seconds
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
/*Client timeout ends*/
final HttpClient client = new DefaultHttpClient(httpParameters);
**********************
//HOW TO SHOW TOAST MESSAGE WHEN THIS CASE ACTUALLY OCCURS ??
You can use try catch block for that.
try{
//your code of making request
}
catch (ConnectTimeoutException e) {
Toast.makeText(context, "Connection timed out.", Toast.LENGTH_SHORT).show();
}
Make sure to pass proper context from Activity.
Hope this helps.

Send pre established post with a toggle android widget

I'm using a PIC as web server it receives a form post to activate and deactivate a relay that is connected to a light bulb. This way I can switch it on and off from a web browser. I'm trying to make a widget in my android in order to control the switch on and off it just needs to send a form post with http basic authentication.
Which would it be the easiest way to achieve this? Since I don't have any android programming skills, I'm been looking in several online sites to build simple android apps but there is none which fill my requirements.
This is what I've used for simple html posting:
String baseurl = "http://yoursite.com" + yourpostdata;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 4000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
////httpClient.setParams(httpParameters); to edit
int timeoutSocket = 8000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient vClient = new DefaultHttpClient(httpParameters);
HttpGet vGet = new HttpGet(baseurl);
String response = "";
try {
ResponseHandler<String> vHandler = new BasicResponseHandler();
response = vClient.execute(vGet, vHandler);
}
catch (Exception e)
{
e.printStackTrace();
}

Android HttpURLConnection disconnect

In my activity i am calling a url using httpurl connection.
In the case when the network strength is very low, i want to disconnect that request.
How can i disconnect an httpurl connection request that is already been sent?
I want to cancel the request when back button is pressed.
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
TIMEOUT IS BASICALLY FOR SLOW CONNECTIONS. After that much time your connection will get disconnected

android using url.openstream isn't throwing IOException if no internet connection. Why?

I am using url.openstream for requesting on to server. In case no internet connection while this, I want data to be stored in database, and hence doing the storage in catch clause of IOException, but instead of being caught here, it just hangs on url.openstream.
I even waited for a minute but, still it didn't get caught in IOException catch clause.
What must I do to overcome this problem?
The problem got solved by using the following method, instead of using url.openstream.
public HttpResponse getResp(String request) throws IOException
{
HttpGet httpGet = new HttpGet(request);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 40000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
return response;
}

Android HttpGet request with a very long URL

I am currently faced to a strange problem.
I have to contact a web service, with a very long URL (there is some XML inside). The length of one of them is 943 characters.
Most of the time, the request failed with a NoHttpResponseException.
I newly added a RetryHandler, which do his job, and the request finally worked, but the execute time was 246 seconds!
I reduced the timeout, to something like 30 seconds, and occasionally, the request work.
Is there something to know about long URL to make it work better?
Or, is it just prohibited on Android?
I precise that all connection with another tinier URL (even like 200 chars) perfectly work.
Here the source code of the Http connection:
DefaultHttpClient hc = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(hc.getParams(), false);
HttpParams httpParameters = hc.getParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
hc.setParams(httpParameters);
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context) {
// retry a max of x times
if(executionCount >= 5){
return false;
}
if(exception instanceof NoHttpResponseException){
return true;
} else if (exception instanceof ClientProtocolException){
return true;
}
return false;
}
};
hc.setHttpRequestRetryHandler(retryHandler);
url = Tool.prepareURL(url);
Log.d(LogFilter.EXECUTE, url);
HttpGet get = new HttpGet(url);
if (eTag != null) {
get.addHeader(HEADER_IF_NONE_MATCH, eTag);
}
long time = System.currentTimeMillis();
HttpResponse rp = hc.execute(get);
Log.d(LogFilter.EXECUTE, "temps execute: "+(System.currentTimeMillis()-time));
return rp;
Thank you for your time.
I think this is a server side problem and may not respond (much) to setting the timeouts. Have you tried pasting the long url into a browser?

Categories

Resources