我的一项 Activity 在启动应用程序时向网络服务发出 http 请求以获取一些天气数据。
由于 Web 服务请求, Activity 需要 3-4 秒才能显示的问题。 (在实际设备上测试)
我知道我没有以正确的方式这样做。我所做的就是在 onCreate 方法上,我发出请求,获取 xml,解析并显示数据。
在 Android 中处理 Web 服务请求的最佳方法是什么,以便应用程序在发出请求时不会显示白屏?也许有一些线程......
我知道我的设备中请求获取实时数据的其他应用程序不会发生这种情况。
注释:
1) 我返回的 xml 不是那么大( 5 个元素,每个元素有 5 个嵌套元素)。
2) 我尝试使用 3G 网络和 Wifi,但响应时间仍然相同。
示例代码:
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.clock_weather);
// this is where it is making the request and parsing the xml.
WeatherSet set = getWeatherCondition("New York, NY");
TextView currentWeather = (TextView) findViewById(R.id.current_weather);
currentWeather.setText("" + set.getWeatherCurrentCondition().getTempFahrenheit());
TextView currentWeatherH = (TextView) findViewById(R.id.current_weatherH);
currentWeatherH.setText("H: " + set.getWeatherForecastConditions().get(0).getTempMaxFahrenheit());
TextView currentWeatherL = (TextView) findViewById(R.id.current_weatherL);
currentWeatherL.setText("L: " + set.getWeatherForecastConditions().get(0).getTempMinFahrenheit());
ImageView currentWeatherIcon = (ImageView) findViewById(R.id.current_weather_icon);
String imageUrl = set.getWeatherCurrentCondition().getIconURL();
Drawable bitmapDrawable = getImageBitmap(imageUrl);
currentWeatherIcon.setImageDrawable(bitmapDrawable);
setForecastInfo(set, R.id.day1, R.id.day1_icon, R.id.day1_temp, 1 );
setForecastInfo(set, R.id.day2, R.id.day2_icon, R.id.day2_temp, 2 );
setForecastInfo(set, R.id.day3, R.id.day3_icon, R.id.day3_temp, 3 );
setForecastInfo(set, R.id.day4, R.id.day4_icon, R.id.day4_temp, 4 );
}
最佳答案
您的响应时间是不可预测的 - 您的网络连接可能非常差,需要几秒钟才能传输几个字节。因此,执行此操作的正确方法(正如您所建议的那样)是使用线程。在我们的例子中,android 提供了非常有用的类来处理这种情况 - AsynTask 。阅读完文档后,您会注意到它有 3 个非常强大的方法可以帮助您
- onPreExecute 在 ui 线程中运行 - 非常有助于显示一些微调器或一些进度指示器,以向用户显示您正在后台执行一些工作
- doInBackground 在后台运行 - 在这里进行后台工作
- onPostExecute 在 ui 线程中运行 - 当您完成后台工作时,隐藏进度并使用新接收到的数据更新 gui。
关于java - Android:由于 Web 服务 Http 请求, Activity 显示时间过长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6719067/