android实现实时天气代码
时间: 2023-12-20 18:03:55 浏览: 25
以下是一个简单的Android实时天气应用程序的示例代码,使用了和风天气API。请注意,您需要在代码中替换您自己的API密钥和城市ID。
MainActivity.java:
```java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView mCityTextView;
private TextView mTemperatureTextView;
private TextView mWeatherTextView;
private ImageView mWeatherIconImageView;
private String mApiKey = "YOUR_API_KEY";
private String mCityId = "YOUR_CITY_ID";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCityTextView = findViewById(R.id.city_text_view);
mTemperatureTextView = findViewById(R.id.temperature_text_view);
mWeatherTextView = findViewById(R.id.weather_text_view);
mWeatherIconImageView = findViewById(R.id.weather_icon_image_view);
new FetchWeatherTask().execute();
}
private class FetchWeatherTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
String apiUrl = "https://free-api.heweather.com/s6/weather/now?location=" + mCityId + "&key=" + mApiKey;
String result = "";
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
}
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject nowObject = jsonObject.getJSONArray("HeWeather6").getJSONObject(0).getJSONObject("now");
String city = jsonObject.getJSONArray("HeWeather6").getJSONObject(0).getJSONObject("basic").getString("location");
String temperature = nowObject.getString("tmp");
String weather = nowObject.getString("cond_txt");
String weatherIconUrl = "https://cdn.heweather.com/cond_icon/" + nowObject.getString("cond_code") + ".png";
mCityTextView.setText(city);
mTemperatureTextView.setText(temperature + " °C");
mWeatherTextView.setText(weather);
RequestOptions options = new RequestOptions()
.placeholder(R.drawable.ic_launcher_background)
.error(R.drawable.ic_launcher_background)
.diskCacheStrategy(DiskCacheStrategy.ALL);
Glide.with(MainActivity.this)
.load(weatherIconUrl)
.apply(options)
.into(mWeatherIconImageView);
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "Failed to parse JSON: " + e.getMessage());
}
}
}
}
```
activity_main.xml:
```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/city_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City"
android:textSize="24sp"
android:textStyle="bold" />
<ImageView
android:id="@+id/weather_icon_image_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="@id/city_text_view"
android:layout_marginTop="16dp" />
<TextView
android:id="@+id/temperature_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="@id/city_text_view"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="Temperature"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/weather_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/weather_icon_image_view"
android:layout_marginTop="16dp"
android:text="Weather"
android:textSize="20sp" />
</RelativeLayout>
```
请注意,这只是一个示例应用程序,您需要根据自己的需求进行修改。此外,您还需要添加网络权限到您的AndroidManifest.xml文件中:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```