安卓APP开发实例:天气预报应用(含API调用)
本教程将通过一个简单的天气预报应用来介绍安卓APP开发和API调用的基本原理及过程。此应用将获取来自网络上的天气信息,并在界面上显示。
### 一、准备工作
1. 开发环境:我们需要安装Android Studio,它是谷歌官方推荐的安卓开发工具,包含了模拟器、SDK、模板等一整套开发、测试工具。
2. API选择:为了获取实时的天气信息,我们需要调用一个公开的天气API。在本教程中,我们将使用OpenWeatherMap(https://openweathermap.org/api)的API。
### 二、创建项目
打开Android Studio,新建一个项目。选择 "Empty Activity" 模板,并为项目命名(例如:WeatherApp)。确认基本设置后点击 "Finish" 完成项目创建。
### 三、导入所需依赖库
由于我们需要调用网络API,并使用JSON数据格式处理天气信息,需要导入相应的库。在 app/build.gradle 文件中添加以下依赖项:
```groovy
dependencies {
// 添加网络请求库
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
```
同步依赖后回到代码编辑界面。
### 四、编写网络请求框架
1. 创建一个包(Package),例如命名为network。在network包下创建一个名为WeatherApiService的接口。
2. 在WeatherApiService中定义一个获取天气信息的方法,使用Retrofit的GET注解请求API接口。
```java
public interface WeatherApiService {
@GET("data/2.5/weather")
Call
@Query("appid") String apiKey,
@Query("units") String units);
}
```
3. 在network包下创建一个名为ApiUtils的类,用于管理API配置。
```java
public class ApiUtils {
public static final String BASE_URL = "https://api.openweathermap.org/";
public static WeatherApiService getWeatherApiService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(WeatherApiService.class);
}
}
```
### 五、创建数据实体
为了解析从API获取的JSON数据,我们需要创建一个Java类来表示天气数据结构。在本例中,我们创建一个名为WeatherResponse的类,用于处理天气信息。
```java
public class WeatherResponse {
@SerializedName("name")
private String cityName;
@SerializedName("main")
private MainWeatherData mainWeatherData;
// 提供getter方法以便外部调用,可自行实现setter方法
public String getCityName() { return cityName; }
public MainWeatherData getMainWeatherData() { return mainWeatherData; }
// 内部类,用于解析更复杂的数据结构
public class MainWeatherData {
@SerializedName("temp")
private float temperature;
public float getTemperature() { return temperature; }
}
}
```
### 六、设计应用界面
1. 打开 activity_main.xml 文件,设计应用的界面。添加所需的EditText、Button和TextView控件,为它们设置ID和属性。
```xml
android:id="@+id/city_input" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入城市名"/>