安卓app开发实例含api调用

安卓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 getWeatherInfo(@Query("q") String cityName,

@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="输入城市名"/>

android:id="@+id/get_weather_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="查询天气"/>

android:id="@+id/weather_info_text"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:padding="16dp"

android:textSize="18sp"/>

```

### 七、编写应用逻辑

1. 在MainActivity中添加找到界面控件的引用,并为按钮添加点击事件监听器。

```java

private EditText cityInput;

private Button getWeatherButton;

private TextView weatherInfoText;

...

cityInput = findViewById(R.id.city_input);

getWeatherButton = findViewById(R.id.get_weather_button);

weatherInfoText = findViewById(R.id.weather_info_text);

getWeatherButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

getWeatherInfo(cityInput.getText().toString());

}

});

```

2. 实现获取天气信息的逻辑。

```java

private void getWeatherInfo(String cityName) {

WeatherApiService apiService = ApiUtils.getWeatherApiService();

// 使用API密钥,可以在OpenWeatherMap网站注册获取

String apiKey = "YOUR_API_KEY";

String units = "metric"; // 单位:摄氏度

Call call = apiService.getWeatherInfo(cityName, apiKey, units);

call.enqueue(new Callback() {

@Override

public void onResponse(Call call, Response response) {

WeatherResponse weatherData = response.body();

if (weatherData != null) {

showWeatherInfo(weatherData);

}

}

@Override

public void onFailure(Call call, Throwable t) {

Toast.makeText(MainActivity.this, "获取天气信息失败",

川公网安备 51019002001728号