Sam*_*mmy 0 java android web-services
当我启动应用程序时,我的一个活动向Web服务发出http请求以获取一些天气数据.
由于Web服务请求,活动将需要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 );
}
Run Code Online (Sandbox Code Playgroud)
您的响应时间是不可预测的 - 您的网络连接可能非常差,并且需要几秒钟才能传输几个字节.所以正确的方法(如你所建议的)是使用线程.在我们的例子中,android提供了非常有用的类来处理这种情况--AsynTask.阅读文档后,您会注意到它有3种非常强大的方法可以帮助您
| 归档时间: |
|
| 查看次数: |
1776 次 |
| 最近记录: |