一、实验目的

  1. 掌握HTTP请求方法
  2. 掌握使用Gson库解析json数据
  3. 熟悉Handler,Message多线程编程步骤
  4. 熟悉OnClickListener监听器的使用

二、实验环境

Windows,android studio 

三、项目分析

该项目是一个天气预报的小程序,主要功能包括:

1、启动程序,显示默认值; 当点击“刷新”按钮时,从Tomcat服务器端读取天气信息(存在服务器端“weather.json”文件中),并更新UI。

2、当点击“刷新”按钮时,从Tomcat服务器端读取天气信息(存在服务器端“weather.json”文件中),并更新UI。

下面,我们来看下效果图,我们将会开了发出一款以下界面的app。

四、实验步骤

1、新建工程。

2、导入需要的图片资源等

3、修改设计主界面

4、实现界面逻辑
1)初始化控件
2)创建WeatherInfo类,存储天气信息
3)实现getWeatherInfo方法在子线程中,实现网络请求,获取数据流
4)实现getInfosFromJson方法完成输入流到对象的转换方法
5)创建Handler对象重写它的HandlerMessage()方法实现UI更新
6)在getWeatherInfo()方法中,补充代码完成处理网络请求得到的响应结果并发送消息7)在OnClickListener监听器的OnClick()方法中,补充代码,调用getWeatherInfo()方法通过网络获取天气信息,再将其转换为天气信息对象列表

接下来我们按步骤完成这个项目的实现。

1、创建工程
File->New->New Project

 


2、导入需要的图片资源
在project工具窗口中,将视图切换到“Project”,然后在res目录下,创建一个drawable-hdpi文件夹;打开“New Resource Directory”窗口,在Resource Type对应的下拉列表中,选择drawable;在左侧“Available qualifies”下方的下拉列表中,选择density,然后点击;然后在density对应的下拉列表中,选择High density,此时就可以看到“Directory Name”自动变为“drawable-hdpi”,然后点击OK;

 将资源文件夹下的四张图片以及xml文件,拷贝到文件夹res/drawable-hdpi下。将weather.json文件放入你存放TomCat路径的Webapps文件夹里(这里我还创建了一个文件夹weather来存放)。

资源下载:https://download.csdn.net/download/weixin_45467625/86151681

 

  

 在res/values/strings.xml:


3.​​​​​​、设计修改主页面:

activity_main.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/tv_city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="40dp"
        android:layout_marginStart="45dp"
        android:text="@string/city"
        android:textSize="50sp"/>
    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignEnd="@id/tv_city"
        android:layout_below="@+id/tv_city"
        android:layout_marginTop="40dp"
        android:paddingBottom="5dp"
        android:src="@drawable/clouds"/>
    <TextView
        android:id="@+id/tv_weather"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/iv_icon"
        android:layout_below="@+id/iv_icon"
        android:layout_marginRight="15dp"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:text="@string/weather"
        android:textSize="18sp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/iv_icon"
        android:layout_toEndOf="@+id/iv_icon"
        android:layout_marginStart="30dp"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_temp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center_vertical"
            android:text="@string/temp"
            android:textSize="22sp"/>
        <TextView
            android:id="@+id/tv_wind"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/wind"
            android:textSize="18sp"/>
        <TextView
            android:id="@+id/tv_pm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/pm"
            android:textSize="18sp"/>
    </LinearLayout>
    <Button
        android:id="@+id/btn_refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        android:text="@string/refresh"/>
</RelativeLayout>

 4、实现界面逻辑

创建WeatherInfo类,存储天气信息

 

 定义成员变量:

在类中,空白行,按alt+insert健(或右键单击,选择Generate),打开Generate窗口,选择Getter and Setter,打开select fields to Generate Getters and Setters窗口,选中所有需要生成get,set方法的域名,点击确定,相应的方法就自动生成了。

 

在子线程中,实现网络请求:在AndroidManifests.xml中开启网络访问权限

 

 在AndroidManifests.xml中,设置Application的属性“usesCleartextTraffic”为true(目标SDKversion为27或更低的应用程序的默认值为“true”。SDKversion是28或更高级别的应用默认为“false”)

 实现从输入流到对象的转换方法:右键单击app,选择open module setting,选择模块app,在右边tab栏中点击Dependency,在右边选择“+”号,选择library dependency,在其中输入Gson,搜索找到“com.google.code.gson:gson:2.8.5”,点击OK,添加Gson依赖。

 MainActivity.java的编写:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class MainActivity extends AppCompatActivity {
//初始化控件和变量
    protected static final int CHANG_UI = 0;
    protected static final int ERROR = 1;
    protected static final int LINK = 2;
    private TextView tvCity;
    private TextView tvWeather;
    private TextView tvTemp;
    private TextView tvWind;
    private TextView tvPm;
    private ImageView ivIcon;
    private int clickCount = 0;

//创建Handler对象,重写它的HandlerMessage()方法,实现UI更新
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == CHANG_UI) {
                List<WeatherInfo> lstWeather = (List<WeatherInfo>)msg.obj;
                if (clickCount<lstWeather.size()) {
                    WeatherInfo objWI = lstWeather.get(clickCount);
                    refreshUI(objWI);
                    clickCount++;
                }
                if (clickCount == lstWeather.size())
                    clickCount = 0;
                Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
            } else if (msg.what == ERROR) {
                Toast.makeText(MainActivity.this, "获取网络数据失败",
                        Toast.LENGTH_SHORT).show();
            }
        }
    };

    private void refreshUI(WeatherInfo objInfo){
        if(objInfo!=null){
              tvCity.setText(objInfo.getCity());
              tvWeather.setText(objInfo.getWeather());
              tvTemp.setText(objInfo.getTemp());
              tvWind.setText(objInfo.getWind());
              tvPm.setText(objInfo.getPm());
              String strWeather=objInfo.getWeather();
        if(strWeather.contains("晴转多云"))
              ivIcon.setImageResource(R.drawable.cloud_sun);
        else if(strWeather.contains("多云"))
              ivIcon.setImageResource(R.drawable.clouds);
        else
              ivIcon.setImageResource(R.drawable.sun);
        }
    }

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

    private void InitView() {
        tvCity = (TextView) findViewById(R.id.tv_city);
        tvWeather = (TextView) findViewById(R.id.tv_weather);
        tvTemp = (TextView) findViewById(R.id.tv_temp);
        tvWind = (TextView) findViewById(R.id.tv_wind);
        tvPm = (TextView) findViewById(R.id.tv_pm);
        ivIcon = (ImageView) findViewById(R.id.iv_icon);

        final String strURL ="http://192.168.10.188:8080/weather/weather.json";

//在OnClickListener监听器的OnClick()方法中,补充代码,调用getWeatherInfo()方法,通过网络获取天气信息,再将其转换为天气信息对象列表
        findViewById(R.id.btn_refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (strURL.isEmpty()){
                    Toast.makeText(MainActivity.this,"路径不能为空",Toast.LENGTH_SHORT).show();
                }else{
                    getWeatherInfo(strURL);
                }
            }
        });
    }

//定义getInfosFromJson方法,实现从InputStream到List<WeatherInfo>的转换
    public List<WeatherInfo> getInfosFromJson(InputStream is) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[4096];
        int count = -1;
        while ((count = is.read(data, 0, 4096)) != -1)
            outStream.write(data, 0, count);
        data = null;
        String json = new String(outStream.toByteArray(), "utf-8");
        //使用gson库解析JSON数据
        Gson gson = new Gson();
        Type listType = new TypeToken<List<WeatherInfo>>() {
        }.getType();
        List<WeatherInfo> weatherInfos = gson.fromJson(json, listType);
        return weatherInfos;
    }

//在getWeatherInfo()方法中,补充代码,完成处理网络请求得到的响应
    public void getWeatherInfo(final String urlPath) {
//子线程请求网络,Android4.0以后访问网络不能放在主线程中
        new Thread() {
            private HttpURLConnection conn;

            public void run() {
                // 连接服务器 get 请求 获取图片
                try {
                    //创建URL对象
                    URL url = new URL(urlPath);
                    // 根据url 发送 http的请求
                    conn = (HttpURLConnection) url.openConnection();
                    // 设置请求的方式
                    conn.setRequestMethod("GET");
                    //设置超时时间
                    conn.setConnectTimeout(5000);
                    // 得到服务器返回的响应码
                    int code = conn.getResponseCode();
                    //请求网络成功后返回码是200
                    if (code == 200) {
                        //获取输入流
                        InputStream is = conn.getInputStream();
                        //解析输入流
                        List<WeatherInfo> lstWeatherInfo = getInfosFromJson(is);
                        if (lstWeatherInfo != null) {
                            //将更改主界面的消息发送给主线程
                            Message msg = new Message();
                            msg.what = CHANG_UI;
                            msg.obj = lstWeatherInfo;
                            handler.sendMessage(msg);
                        }
                    } else {
                        //返回码不等于200 请求服务器失败
                        Message msg = new Message();
                        msg.what = ERROR;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = ERROR;
                    handler.sendMessage(msg);
                }
                //关闭连接
                conn.disconnect();
            }
        }.start();
    }
}

 5、调试、运行

 

最后附上源码:https://download.csdn.net/download/weixin_45467625/87301318

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐