Android开发获取城市的天气信息

在移动应用开发中,天气应用是一个经典的项目,它不仅帮助用户获取实时天气信息,还能提升开发者的实战技能。本文将介绍如何在Android平台上实现一个简单的天气查询应用,展示获取城市天气信息的方式,并提供相关代码示例。

一、项目准备

1.1 创建Android项目

首先,你需要使用Android Studio创建一个新的项目。选择 "Empty Activity" 模板,命名为 "WeatherApp"。

1.2 添加依赖库

为了简化HTTP请求和JSON解析,我们可以使用Retrofit和Gson库。打开 build.gradle 文件,添加如下依赖:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.8'

添加完依赖后,点击 "Sync Now" 以同步项目。

二、获取天气数据的API

在这里,我们将使用一个免费的天气API,例如OpenWeatherMap。首先,你需要到 [OpenWeatherMap]( 注册并获取一个API密钥。我们将使用以下API请求格式:

 name}&appid={API key}&units=metric

其中,{city name} 是城市的名称,{API key} 是你的API密钥。

三、创建数据模型

为了处理API返回的数据,我们需要创建一个数据模型。我们将创建一个类 WeatherResponse 来对应API的响应。

public class WeatherResponse {
    private Main main;
    private String name;

    public Main getMain() {
        return main;
    }

    public String getName() {
        return name;
    }

    public class Main {
        private float temp;
        private float humidity;

        public float getTemp() {
            return temp;
        }

        public float getHumidity() {
            return humidity;
        }
    }
}

四、设置Retrofit

接下来,我们创建一个API接口 WeatherApi 以及Retrofit实例。

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface WeatherApi {
    @GET("data/2.5/weather")
    Call<WeatherResponse> getWeather(@Query("q") String city, @Query("appid") String apiKey, @Query("units") String units);
}

MainActivity 中设置Retrofit实例:

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    private static final String BASE_URL = "
    private WeatherApi weatherApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        weatherApi = retrofit.create(WeatherApi.class);
    }
}

五、实现天气查询功能

创建一个简单的用户界面包含一个EditText来输入城市名和一个Button来触发天气查询。可以在 activity_main.xml 文件中添加如下布局:

<LinearLayout xmlns:android="
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/cityInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter city name" />

    <Button
        android:id="@+id/getWeatherButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Weather" />

    <TextView
        android:id="@+id/weatherInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="16dp" />
</LinearLayout>

接下来,在 MainActivity 中处理Button的点击事件并发起API请求:

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private EditText cityInput;
    private TextView weatherInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cityInput = findViewById(R.id.cityInput);
        weatherInfo = findViewById(R.id.weatherInfo);
        Button getWeatherButton = findViewById(R.id.getWeatherButton);

        getWeatherButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchWeather();
            }
        });
    }

    private void fetchWeather() {
        String city = cityInput.getText().toString().trim();
        String apiKey = "YOUR_API_KEY"; // 请替换为你的API密钥

        weatherApi.getWeather(city, apiKey, "metric").enqueue(new Callback<WeatherResponse>() {
            @Override
            public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    WeatherResponse weatherResponse = response.body();
                    String weatherData = "城市: " + weatherResponse.getName() +
                                         "\n温度: " + weatherResponse.getMain().getTemp() + "°C" +
                                         "\n湿度: " + weatherResponse.getMain().getHumidity() + "%";
                    weatherInfo.setText(weatherData);
                } else {
                    Toast.makeText(MainActivity.this, "未找到该城市", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WeatherResponse> call, Throwable t) {
                Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

六、展示旅行路线

最后,为了使应用更加有趣,可以在应用中加入一段旅行图,展示用户的旅行路线。我们用Mermaid语法来展示旅行图:

journey
    title 旅行路线
    section 启程
      出发地: 5: 着想进行旅行
    section 途中
      魅力城市A: 5: 游览历史古迹
      魅力城市B: 5: 享受美食
    section 目的地
      到达目的地: 5: 开始新的旅程

结尾

通过以上的步骤,我们实现了一个简单的天气查询应用,用户可以方便地获取指定城市的天气信息。在开发过程中,我们使用了Retrofit库来处理网络请求,并采用了数据模型来解析JSON响应。

随着开发技能的提升,您可以进一步扩展这个应用,添加更多功能,比如天气预报、不同城市的天气比较、天气图标等。希望这篇文章能帮助您在Android开发之旅中取得更好的进展!如果你有任何问题,欢迎随时讨论。