当前位置:   article > 正文

鸿蒙harmony天气预报Demo_鸿蒙天气预报app代码

鸿蒙天气预报app代码

1.准备工作

1.1创建项目

在这里插入图片描述

sdk为6版本,所以使用华为的远程模拟器p40即可。

1.2准备图片资源

这里把天气预报用到的天气提示的图片全放在资源目录下的media文件下。

具体资源在github仓库已包含,自行前往。

1.3配置文件

接着是修改配置文件,由于是发送网络请求请求api获取json天气数据,所以和安卓一样,需要修改配置文件,添加网络请求权限。

修改config.json,在module节点添加如下权限。

"reqPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  },
  {
    "name": "ohos.permission.GET_NETWORK_INFO"
  },
  {
    "name": "ohos.permission.SET_NETWORK_INFO"
  }
],
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

接着还要配置http协议的api也能正常访问。在module和app同级添加如下。

"deviceConfig": {
  "default": {
    "network": {
      "cleartextTraffic": true
    }
  }
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

如果想要去除页面顶部的标题区域,接着添加如下配置。

"metaData": {
  "customizeData": [
    {
      "name": "hwc-theme",
      "value": "androidhwext:style/Theme.Emui.NoTitleBar"
    }
  ]
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

最后添加完成预览:
在这里插入图片描述

2.网络请求工具类

天气api以前文章提到过,自行前往–>简易的安卓天气app(一)——解析Json数据、数据类封装

最后得到的api形式为:

https://tianqiapi.com/api?version=v1&appid={your appid}&appsecret={your appsecret}
  • 1

其中appid和appsecret需要自行申请,免费版有请求上限。

此api会默认根据访问者ip的地理位置进行定位。又因为虚拟手机没法获取设备位置且本人没有华为设备,没法加入定位功能,,所以暂时在代码中指定需要查询的城市,,,

2.1NetworkUtil

网络请求工具类,返回api获取的string字符串就行

public class NetworkUtil {
    /**
     * 18625561:27XjzrB7
     * 67342285:5XgTk31r
     * 19267789:Dhu3DShY
     */
    public static final String URL_WEATHER = "https://tianqiapi.com/api?version=v1&appid=67342285&appsecret=5XgTk31r";

    public static String httpGet(String cityName) {
        String urlGetJson = URL_WEATHER + "&city=" + cityName;
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL(urlGetJson);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);
            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String temp;
            while ((temp = reader.readLine()) != null) {
                sb.append(temp);
            }
            reader.close();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return sb.toString();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

2.2测试网络请求

为了保证主线程不受干扰,网络请求需要单独开辟一个异步线程请求数据。详情前往鸿蒙开发指南线程管理开发指导

创建一个异步线程:(使用lamda编程,不再new Runnable()实现 )

TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
globalTaskDispatcher.asyncDispatch(() -> {
	//网络请求,城市名指定即可,此处指定北京
    //String result = NetworkUtil.httpGet(cityName);
    String result = NetworkUtil.httpGet("北京");
    System.out.println(result);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

成功获取数据:

在这里插入图片描述

2.3api返回数据结构

在这里插入图片描述

3.实体类封装

需要两个实体类封装数据:

在这里插入图片描述

WeatherBean封装城市名称更新时间即可,其中还包含DayWeatherBean的数组存放七天天气。

DayWeatherBean就是七天的每一天的天气详情,每天的天气还包含24小时详细天气,本文不再详细探讨。

public class WeatherBean implements Serializable {

    @SerializedName("cityid")
    private String cityid;

    private String city;//城市名称

    private String update_time;//更新时间

    private List<DayWeatherBean> data;//获取今日天气,get[0]
    // get set toString。。。
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
public class DayWeatherBean implements Serializable {
    @SerializedName("date")
    private String date;
    private String wea;//天气
    private String wea_img;//天气图标
    private String week;//周几
    private String tem;//温度
    //tv_tem_low_high=tem2+tem1拼接一起
    private String tem2;//低温
    private String tem1;//高温
    //tv_win=win+win_speed
    private String[] win;//风力
    private String win_speed;//风力等级
    //tv_air=air+air_level+air_tips拼接一起
    private String air;//
    private String air_level;//
    private String air_tips;//

//    @SerializedName("hours")
//    private List<HoursWeatherBean> hoursWeatherBeanList;

//    @SerializedName("index")
//    private List<TipsBean> mTipsBeans;

    // get set toString。。。
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

封装数据使用Google的gson进行

首先引入gson依赖:打开build.gradle添加依赖,别忘了右上角Sync Now同步一下

implementation 'com.google.code.gson:gson:2.8.5'
  • 1

在这里插入图片描述

对获取到的数据result进行封装:得到WeatherBean对象

Gson gson = new Gson();
WeatherBean weatherBean = gson.fromJson(result, WeatherBean.class);
  • 1
  • 2

在这里插入图片描述

之后就是把数据渲染到ui上即可。

4.ui

4.1首页ui设计

使用StackLayout把壁纸放在最下面一层,接着就是DirectionalLayout布局。

使用ScrollView组件包裹DirectionalLayout可以使布局上下滑动,超出屏幕布局可滑动屏幕查看。

在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<StackLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent">

    <Image
        ohos:id="$+id:bg"
        ohos:height="match_parent"
        ohos:width="match_parent"
        ohos:background_element="$media:bg"
        ohos:scale_mode="center"/>

    <DirectionalLayout
        ohos:height="match_parent"
        ohos:width="match_parent"
        ohos:orientation="vertical">

        <!--头部bar-->
        <DirectionalLayout
            ohos:height="match_content"
            ohos:width="match_parent"
            ohos:bottom_margin="8vp"
            ohos:orientation="horizontal"
            ohos:top_margin="8vp">

            <Image
                ohos:id="$+id:add"
                ohos:height="30vp"
                ohos:width="30vp"
                ohos:image_src="$media:add"
                ohos:layout_alignment="horizontal_center"
                ohos:left_margin="20vp"
                ohos:scale_mode="clip_center"/>

            <Text
                ohos:id="$+id:text_city"
                ohos:height="match_parent"
                ohos:width="260vp"
                ohos:layout_alignment="horizontal_center"
                ohos:text="郑州"
                ohos:text_alignment="horizontal_center"
                ohos:text_color="#000"
                ohos:text_size="26fp"/>

            <Image
                ohos:id="$+id:more"
                ohos:height="30vp"
                ohos:width="30vp"
                ohos:image_src="$media:more"
                ohos:layout_alignment="horizontal_center"
                ohos:right_margin="20vp"
                ohos:scale_mode="clip_center"/>

        </DirectionalLayout>

        <!--分割白横线-->
        <ProgressBar
            ohos:id="$+id:progressbar"
            ohos:height="6vp"
            ohos:width="match_parent"
            ohos:max="100"
            ohos:min="0"
            ohos:progress="100"
            ohos:progress_element="#FFF6F0F0"
            ohos:progress_width="10vp"/>

        <ScrollView
            ohos:rebound_effect="true"
            ohos:height="match_parent"
            ohos:width="match_parent">

        <DirectionalLayout
            ohos:height="match_parent"
            ohos:width="match_parent"
            ohos:layout_alignment="horizontal_center"
            ohos:orientation="vertical"
            ohos:top_margin="10vp"
            >
            <!--ohos:scale_mode="stretch"表示将原图缩放到与Image大小一致-->
            <Image
                ohos:id="$+id:weather_img"
                ohos:height="100vp"
                ohos:width="120vp"
                ohos:image_src="$media:weather_yin"
                ohos:layout_alignment="horizontal_center"
                ohos:scale_mode="stretch"/>

            <Text
                ohos:id="$+id:text_weather"
                ohos:height="match_content"
                ohos:width="match_content"
                ohos:layout_alignment="horizontal_center"
                ohos:text="阴转多云"
                ohos:text_color="#000"
                ohos:text_size="20fp"/>

            <Text
                ohos:id="$+id:text_tem"
                ohos:height="match_content"
                ohos:width="match_content"
                ohos:layout_alignment="horizontal_center"
                ohos:text="26°C"
                ohos:text_color="#000"
                ohos:text_size="50fp"/>

            <Text
                ohos:id="$+id:text_tem_low_high"
                ohos:height="match_content"
                ohos:width="match_content"
                ohos:layout_alignment="horizontal_center"
                ohos:text="20°C/30°C"
                ohos:text_color="#000"
                ohos:text_size="20fp"/>

            <Text
                ohos:id="$+id:text_week"
                ohos:height="match_content"
                ohos:width="match_content"
                ohos:layout_alignment="horizontal_center"
                ohos:text="星期日"
                ohos:text_color="#000"
                ohos:text_size="20fp"/>

            <!--风向以及出行建议-->
            <DirectionalLayout
                ohos:height="match_content"
                ohos:width="match_parent"
                ohos:left_margin="10vp"
                ohos:right_margin="10vp"
                ohos:top_padding="6vp"
                ohos:bottom_padding="6vp"
                ohos:background_element="$graphic:background_ability_main"
                ohos:layout_alignment="horizontal_center"
                ohos:orientation="horizontal"
                >
                <!--左侧-->
                <DirectionalLayout
                    ohos:height="match_content"
                    ohos:width="match_content"
                    ohos:left_margin="10vp"
                    ohos:right_margin="10vp"
                    ohos:layout_alignment="horizontal_center"
                    ohos:orientation="vertical"
                    >
                    <Image
                        ohos:height="60vp"
                        ohos:width="60vp"
                        ohos:image_src="$media:fengli"
                        ohos:layout_alignment="horizontal_center"
                        ohos:scale_mode="stretch"/>
                    <Text
                        ohos:id="$+id:text_win"
                        ohos:height="match_content"
                        ohos:width="match_content"
                        ohos:layout_alignment="horizontal_center"
                        ohos:text="西北风3~4级"
                        ohos:text_color="#fff"
                        ohos:text_size="16fp"/>
                </DirectionalLayout>
                <!--右侧-->
                <DirectionalLayout
                    ohos:height="match_content"
                    ohos:width="match_parent"
                    ohos:left_margin="10vp"
                    ohos:right_margin="10vp"
                    ohos:layout_alignment="horizontal_center"
                    ohos:orientation="vertical"
                    >
                    <!--空气质量-->
                    <DirectionalLayout
                        ohos:height="match_content"
                        ohos:width="match_parent"
                        ohos:orientation="horizontal"
                        ohos:layout_alignment="horizontal_center"
                        ohos:alignment="right"
                        >
                        <Image
                            ohos:height="30vp"
                            ohos:width="30vp"
                            ohos:image_src="$media:kongqi"
                            ohos:layout_alignment="horizontal_center"
                            ohos:scale_mode="stretch"/>
                        <Text
                            ohos:id="$+id:text_air"
                            ohos:height="match_content"
                            ohos:width="match_content"
                            ohos:layout_alignment="horizontal_center"
                            ohos:text="43 | 优"
                            ohos:text_color="#fff"
                            ohos:text_size="16fp"/>

                    </DirectionalLayout>

                    <!--出行建议-->
                    <DirectionalLayout
                        ohos:height="match_content"
                        ohos:width="match_parent"
                        >
                        <Text
                            ohos:id="$+id:text_tips"
                            ohos:height="match_parent"
                            ohos:width="match_content"
                            ohos:multiple_lines="true"
                            ohos:max_text_lines="3"
                            ohos:truncation_mode="ellipsis_at_end"
                            ohos:text="儿童、老年人及心脏病、呼吸系统疾病患者应尽量减少体力消耗大的户外活动。"
                            ohos:text_color="#FF9F02FF"
                            ohos:text_size="13fp"/>

                    </DirectionalLayout>

                </DirectionalLayout>

            </DirectionalLayout>

            <ListContainer
                ohos:id="$+id:list_container"
                ohos:height="match_content"
                ohos:width="match_parent"
                ohos:left_margin="10vp"
                ohos:right_margin="10vp"
                ohos:top_margin="10vp"
                ohos:top_padding="6vp"
                ohos:bottom_padding="6vp"
                ohos:background_element="$graphic:background_ability_main"
                ohos:layout_alignment="horizontal_center"
                ohos:orientation="vertical"/>

        </DirectionalLayout>
        </ScrollView>

    </DirectionalLayout>

</StackLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235

还包含一个ListContainer渲染未来七天天气数据。list_item的模板设计:

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="40vp"
    ohos:width="match_parent"
    ohos:left_margin="20vp"
    ohos:right_margin="20vp"
    ohos:orientation="horizontal"
    ohos:alignment="horizontal_center">
    <Text
        ohos:id="$+id:text_date"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:weight="1"
        ohos:text="11-11"
        ohos:text_color="#fff"
        ohos:text_size="20fp"/>
    <Image
        ohos:id="$+id:day_weather_img"
        ohos:height="30vp"
        ohos:width="30vp"
        ohos:weight="1"
        ohos:image_src="$media:weather_yin"
        ohos:scale_mode="inside"/>
    <Text
        ohos:id="$+id:text_tem_low_high"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text_alignment="right"
        ohos:weight="1"
        ohos:text="20°C/30°C"
        ohos:text_color="#fff"
        ohos:text_size="20fp"/>
</DirectionalLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

实现效果:

在这里插入图片描述

4.2获取图片位置工具

获取到api返回的数据后,把数据封装成实体类,其中wea_img属性接受一个string字符串,判断字符串的值返回对应图片资源的int整型。

package com.roydon.weatherforcast.utils;

import com.roydon.weatherforcast.ResourceTable;

public class WeatherImgUtil {

    public static int getImgResOfWeather(String weaStr) {
        int result = 0;
        switch (weaStr) {
            case "qing":
                result = ResourceTable.Media_weather_yin;
                break;
            case "yin":
                result = ResourceTable.Media_weather_yin;
                break;
            case "yu":
                result = ResourceTable.Media_weather_dayu;
                break;
            case "yun":
                result = ResourceTable.Media_weather_duoyun;
                break;
            case "bingbao":
                result = ResourceTable.Media_weather_leizhenyubingbao;
                break;
            case "wu":
                result = ResourceTable.Media_weather_wu;
                break;
            case "shachen":
                result = ResourceTable.Media_weather_shachenbao;
                break;
            case "lei":
                result = ResourceTable.Media_weather_leizhenyu;
                break;
            case "xue":
                result = ResourceTable.Media_weather_daxue;
                break;
            default:
                result = ResourceTable.Media_weather_qing;
                break;
        }
        return result;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

4.3渲染数据

组件全部注册好之后,封装一个渲染数据的方法。

public void dataShow(WeatherBean weatherBean) {
    if (weatherBean == null) {
        return;
    }
    city.setText(weatherBean.getCity());
    DayWeatherBean dayWeather = weatherBean.getData().get(0);//当天天气
    if (dayWeather == null) {
        return;
    }
    // 当天天气
    weatherImg.setPixelMap(WeatherImgUtil.getImgResOfWeather(dayWeather.getWea_img()));
    weather.setText(dayWeather.getWea());
    tem.setText(dayWeather.getTem());
    temLowHigh.setText(dayWeather.getTem2() + "/" + dayWeather.getTem1());
    week.setText(dayWeather.getWeek());
    win.setText(dayWeather.getWin()[0] + dayWeather.getWin_speed());
    air.setText(dayWeather.getAir() + " | " + dayWeather.getAir_level());
    tips.setText("
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/296601
推荐阅读
相关标签