Reputation: 1370
The code I currently have submits data successfully to a database when there is a network connection. My app is one that would be used outdoors, frequently in places were cell service is very poor.
My question is what would be the best way to delay the HTTP Post until there is an active network connection? Should I create a service that is run if there is no connection that is alerted when a connection is available? The data transmitted is small, around a kilobyte, so I could just have the app store it until the device is online and then submit the data. Does this seem workable?
Another, poorer, option, would be to have the app store the data and check everytime it is started if there is any data still waiting to be submitted and an active connection to submit it with.
The code I currently have to submit the data is below. If you have any suggestions on it, those would be more than welcome as well.
String setPost(Context context)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(context.getResources().getString(R.string.url));
try
{
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(22);
nameValuePairs.add(new BasicNameValuePair("month", "7"));
... etc ...
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte)current);
}
Toast.makeText(context, "thank you for submitting!", Toast.LENGTH_LONG).show();
return new String(baf.toByteArray());
}
catch (ClientProtocolException e)
{
Log.e(this.toString(), "fail: " + e);
Toast.makeText(context, "submission failed :(\n please report the error below to developer\n" + e.toString(), Toast.LENGTH_LONG).show();
return ("fail: " + e);
}
catch (IOException e)
{
Log.e(this.toString(), "fail: " + e);
Toast.makeText(context, "submission failed :(\n please report the error below to developer:\n" + e.toString(), Toast.LENGTH_LONG).show();
return ("fail: " + e);
}
Upvotes: 0
Views: 504
Reputation: 48871
Should I create a service that is run if there is no connection that is alerted when a connection is available?
Yes. Use an IntentService
to handle all network requests. When an Activity
wants to upload/download anything, it passes its request to the IntentService
. If there is no network connection, the request is queued and the IntentService
terminates itself.
Also create a BroadcastReceiver
registered in the mainifest which 'listens' for network connectivity changes. If the change is to a 'connected' state, it should start the IntentService
which processes any queued network requests and again self-terminates.
It's efficient and works well in my experience.
Upvotes: 2