基于Androidstudio推荐一个简易的天气预报app源码
时间: 2023-10-10 21:13:15 浏览: 116
以下是一个简单的天气预报应用程序的Android Studio源代码示例,您可以根据需要进行修改:
```
public class MainActivity extends AppCompatActivity {
private TextView cityText;
private TextView condDescr;
private TextView temp;
private TextView press;
private TextView windSpeed;
private TextView windDeg;
private TextView hum;
private ImageView imgView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityText = (TextView) findViewById(R.id.cityText);
condDescr = (TextView) findViewById(R.id.condDescr);
temp = (TextView) findViewById(R.id.temp);
hum = (TextView) findViewById(R.id.hum);
press = (TextView) findViewById(R.id.press);
windSpeed = (TextView) findViewById(R.id.windSpeed);
windDeg = (TextView) findViewById(R.id.windDeg);
imgView = (ImageView) findViewById(R.id.condIcon);
String city = "London,UK";
String key = "your_api_key";
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + key;
new WeatherTask().execute(url);
}
private class WeatherTask extends AsyncTask<String, Void, Weather> {
@Override
protected Weather doInBackground(String... params) {
String data = ((new WeatherHttpClient()).getWeatherData(params[0]));
Weather weather = JSONWeatherParser.getWeather(data);
return weather;
}
@Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather != null) {
cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "°C");
hum.setText("" + weather.currentCondition.getHumidity() + "%");
press.setText("" + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText("" + weather.wind.getSpeed() + " m/s");
windDeg.setText("" + weather.wind.getDeg() + "°");
condDescr.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
Picasso.with(MainActivity.this).load(weather.currentCondition.getIconURL()).into(imgView);
}
}
}
}
```
请注意,在上述代码示例中,您需要使用自己的API密钥,您可以从OpenWeatherMap网站上获得。另外,您需要在布局文件中定义必要的TextView和ImageView元素,以便在代码中引用它们。
阅读全文