android - 在 android 2.1 中从服务器下载数据

标签 android service

我想下载一些保存在我的在线服务器上的联系人,然后在我的 Activity 中显示它们。我已经编写了一项服务,并且我正在提供来自 onStartCommand 函数的代码 fragment ,其中正在完成此下载。

public int onStartCommand(Intent intent, int flags, int startId)
{
    String responseStr = "";
    try
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(URL);          

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("action", "get_contact"));
        nameValuePairs.add(new BasicNameValuePair("uId", uId + ""));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse httpResponse = httpClient.execute(httpPost);

        BufferedReader in = new BufferedReader (new InputStreamReader(httpResponse.getEntity().getContent()));
        responseStr = in.readLine();        
        in.close();
    }
    catch (ClientProtocolException e)
    {
        Log.e("EXCEPTION", "ClientProtocolException");
    }
    catch (IOException e)
    {
        Log.e("EXCEPTION", "IOException");
    }
    this.stopSelf();

    return Service.START_STICKY;
}

但是这段代码的问题是下载数据花费的时间太长了。请建议我以任何方式快速下载并在我的 Activity 中显示此数据。

预先感谢您的帮助。

最佳答案

嗯,如果您的服务器或连接速度很慢,您的客户端代码就无能为力了。

但是,您绝对应该考虑压缩来自 Web 服务器的响应,并在客户端代码上添加 header :

接受编码:gzip

关于android - 在 android 2.1 中从服务器下载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548751/

相关文章:

android - 在 WebView 中加载本地 html?

java - getSharedPreferences 上的 Android SharedPreferences NullPointerException

android - 服务在销毁后被创建两次

Android服务在应用程序被杀死时重新启动

android - 确定用户是否选择 Facebook 作为社交分享选项

android - SupportFragmentManager, popbackstack & screen rotation

android - PhoneStateListener onSignalStrengthsChanged 停止在服务中被调用

Android服务服务崩溃2次,停止: ServiceRecord

android - 用错误 “SSL error when connecting to the Jack server. Try ' jack-diagnose 重建 android 代码”

android - 在后台上传文件,服务?