2012-07-09 51 views
0

当前有代码在网络连接时成功向数据库提交数据。我的应用程序是一个可以在户外使用的应用程序,经常在服务非常差的地方使用。HTTP Post延迟至在线

我的问题是延迟HTTP Post的最佳方式是什么,直到存在活动的网络连接?我应该创建一个在没有连接时会运行的服务吗?传输的数据很小,大约一千字节,所以我可以让应用程序存储它直到设备在线,然后提交数据。这看起来可行吗?

另一个更穷的选择是让应用程序存储数据,并在每次启动数据时检查是否有任何数据仍在等待提交,并提供一个活动连接进行提交。

我目前需要提交数据的代码如下。如果您对此有任何建议,那么这些也不会受到欢迎。

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); 
    } 

回答

2

我应该创建一个运行,如果没有当连接可用被惊动连接的服务?

是的。使用IntentService来处理所有网络请求。当Activity想要上传/下载任何东西时,它将其请求传递给IntentService。如果没有网络连接,则请求排队并且IntentService自行终止。

另外创建一个BroadcastReceiver注册在mainifest中'监听'网络连接变化。如果更改处于“已连接”状态,则应启动IntentService,它处理任何排队的网络请求并再次自行终止。

它的效率和效果很好,以我的经验。