Android实现-心知天气API接口开发(天气预报app)

这篇具有很好参考价值的文章主要介绍了Android实现-心知天气API接口开发(天气预报app)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

自己开发app之心知天气APP程序代码粘贴即可用。完整代码附最后。


一、环境配置和素材准备

第一步:去知心天气注册开发者账号查看自己的token。注册好登录进去--控制台---免费版--秘钥。这里的秘钥就是自己的token。(有兴趣的可以看开发文档,这里就不多介绍了)

Android实现-心知天气API接口开发(天气预报app)

 第二步,下载素材包。点击文档-跳转至v3文档--开始使用--天气现象代码说明。点击超链接下载img素材包。

Android实现-心知天气API接口开发(天气预报app)

 下载好的素材包需要更改一下名称,如果直接导入安卓项目里会报错。名称以字母开头如1.jpg就改成a1.jpg。改完名称后,全选复制到安卓项目里的。右击drawable,选择粘贴。如图所示:

Android实现-心知天气API接口开发(天气预报app)

给Android虚拟机申请网络权限如图所示:

网路权限:<uses-permission android:name="android.permission.INTERNET"/>

Android实现-心知天气API接口开发(天气预报app)添加第三方依赖okhttp:

implementation 'com.squareup.okhttp3:okhttp:3.4.1'

Android实现-心知天气API接口开发(天气预报app)

 二、代码讲解

接下来就是上代码了(只讲关键代码,其余不懂的可以私信问我也可以百度):

  private int[] image={R.drawable.a0,R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,R.drawable.a8,R.drawable.a9,R.drawable.a10,R.drawable.a11,R.drawable.a12,R.drawable.a13,R.drawable.a14,R.drawable.a15,R.drawable.a16,R.drawable.a17,R.drawable.a18,R.drawable.a19,R.drawable.a20,
         R.drawable.a21,R.drawable.a22,R.drawable.a23,R.drawable.a24,R.drawable.a25,R.drawable.a26,R.drawable.a27,R.drawable.a28,R.drawable.a29,R.drawable.a30,R.drawable.a31,R.drawable.a32,
            R.drawable.a33, R.drawable.a34, R.drawable.a35, R.drawable.a36, R.drawable.a37, R.drawable.a38, R.drawable.a99};

将刚刚导入的img文件做成int[]数组,这样做的好处是便于访问img资源,将天气图标显示到activity上,当然也有其他办法可以百度。

封装请求函数以及JSON解析:

根据文档得知请求的URL是: "https://api.seniverse.com/v3/weather/now.json?key=(这里是你的token)"+所查询要的地区+"&language=zh-Hans&unit=c"请求方法是get。因为考虑到网络原因,避免系统因为网络延迟卡死,故在这里开了一个线程。

new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(
                        "https://api.seniverse.com/v3/weather/now.json?key=SVfFen6tRMSdvu0D4&location="+
                                ed1.getText().toString()+"&language=zh-Hans&unit=c"
                ).build();

解析JSON:

 Response response = okHttpClient.newCall(request).execute();
                    String responsestr = response.body().string();
                    JSONObject object = new JSONObject(responsestr);
                    JSONArray resultsarry = object.getJSONArray("results");
                    JSONObject now = resultsarry.getJSONObject(0).getJSONObject("now");
                    JSONObject location =resultsarry.getJSONObject(0).getJSONObject("location");
                    weatherText = now.getString("text");
                    weatherCode = now.getString("code");
                    weatherTemperature = now.getString("temperature");
                    diqu=location.getString("name");

开线程以及消息处理:

因为Android在线程里不能更新ui界面,否则会闪退。需要更新ui就用到了安卓的消息处理机制,通过handleMessage来更新ul界面。通过bundle将解析的数据传送给myhandle,实现UI更新。

  Bundle bundle = new Bundle();
                    bundle.putString("text", weatherText);
                    bundle.putString("code", weatherCode);
                    bundle.putString("temperature", weatherTemperature);
                    bundle.putString("loc",diqu);
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = bundle;
                    myHandler.sendMessage(msg);
 MyHandler myHandler = new  MyHandler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                Bundle bundle =(Bundle)msg.obj;
                tv2.setText(bundle.getString("text"));
                tv3.setText(bundle.getString("temperature")+"℃");
                tv1.setText("当前地区:"+bundle.getString("loc"));
                iv1.setImageResource(image[Integer.valueOf(bundle.getString("code")).
                            intValue()]);
            }
        }
    };

最终效果:

Android实现-心知天气API接口开发(天气预报app)文章来源地址https://www.toymoban.com/news/detail-436146.html

三、完整代码

mainactivity代码:

package com.example.shixun;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
import static android.widget.Toast.LENGTH_LONG;
public class MainActivity extends AppCompatActivity {
    private TextView tv1,tv2,tv3;
    private Button b1;
    private ImageView iv1;
    private EditText ed1;
    private  String weatherText,weatherCode,weatherTemperature,diqu;
    private int[] image={R.drawable.a0,R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,R.drawable.a8,R.drawable.a9,R.drawable.a10,R.drawable.a11,R.drawable.a12,R.drawable.a13,R.drawable.a14,R.drawable.a15,R.drawable.a16,R.drawable.a17,R.drawable.a18,R.drawable.a19,R.drawable.a20,
            R.drawable.a21,R.drawable.a22,R.drawable.a23,R.drawable.a24,R.drawable.a25,R.drawable.a26,R.drawable.a27,R.drawable.a28,R.drawable.a29,R.drawable.a30,R.drawable.a31,R.drawable.a32,
            R.drawable.a33, R.drawable.a34, R.drawable.a35, R.drawable.a36, R.drawable.a37, R.drawable.a38, R.drawable.a99};
    public  class MyHandler extends Handler{
        public MyHandler(){
        }
    }
    MyHandler myHandler = new  MyHandler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                Bundle bundle =(Bundle)msg.obj;
                tv2.setText(bundle.getString("text"));
                tv3.setText(bundle.getString("temperature")+"℃");
                tv1.setText("当前地区:"+bundle.getString("loc"));
                iv1.setImageResource(image[Integer.valueOf(bundle.getString("code")).
                            intValue()]);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1=(TextView)this.findViewById(R.id.tv1);
        tv2=(TextView)this.findViewById(R.id.tv2);
        tv3=(TextView)this.findViewById(R.id.tv3);
        b1=(Button) this.findViewById(R.id.b1);
        iv1= (ImageView) this.findViewById(R.id.iv1);
 ed1=(EditText) this.findViewById(R.id.ed1);
ed1.setText("无锡");
       // sendHttpRequest();
b1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        sendHttpRequest();
        Toast.makeText(MainActivity.this,"11",Toast.LENGTH_LONG).show();
    }
});
    }
    public void sendHttpRequest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(
                        "https://api.seniverse.com/v3/weather/now.json?key=SVfFen6tRMSdvu0D4&location="+
                                ed1.getText().toString()+"&language=zh-Hans&unit=c"
                ).build();
                try {
                    Response response = okHttpClient.newCall(request).execute();                    String responsestr = response.body().string();
                    JSONObject object = new JSONObject(responsestr);
                    JSONArray resultsarry = object.getJSONArray("results");
                    Log.d("JYPC", resultsarry+"sac");
                    JSONObject now = resultsarry.getJSONObject(0).getJSONObject("now");
                    JSONObject location =resultsarry.getJSONObject(0).getJSONObject("location");
                    weatherText = now.getString("text");
                    weatherCode = now.getString("code");
                    weatherTemperature = now.getString("temperature");
                    diqu=location.getString("name");
                    Bundle bundle = new Bundle();
                    bundle.putString("text", weatherText);
                    bundle.putString("code", weatherCode);
                    bundle.putString("temperature", weatherTemperature);
                    bundle.putString("loc",diqu);
                    Log.d("JYPC", diqu+"sac");
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = bundle;
                    myHandler.sendMessage(msg);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }

}

xml代码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        tools:layout_editor_absoluteX="6dp"
        tools:ignore="MissingConstraints">

        <TextView
            android:id="@+id/tv1"
            android:layout_width="match_parent"
            android:textSize="30dp"
            android:textColor="#000000"
            android:layout_height="52dp"
            android:layout_gravity="center_vertical"
            android:text="实况" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="72dp"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/ed1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:textSize="30dp"
                android:textColor="#000000"
                android:text="" />

            <Button
                android:id="@+id/b1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:textSize="20dp"
                android:textColor="#2f4f4f"
                android:text="查询" />
        </LinearLayout>

        <TextView
            android:id="@+id/tv2"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginLeft="150dp"
            android:textSize="30dp"
            android:textColor="#000000"
            android:gravity="center"
            android:text="天气状况"></TextView>

        <ImageView
            android:id="@+id/iv1"
            android:layout_width="match_parent"
            android:layout_height="381dp">

        </ImageView>

        <TextView
            android:id="@+id/tv3"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:layout_marginLeft="150dp"
            android:textSize="30dp"
            android:textColor="#000000"
            android:gravity="center"
            android:text="温度"></TextView>


    </LinearLayout>



</androidx.constraintlayout.widget.ConstraintLayout>

到了这里,关于Android实现-心知天气API接口开发(天气预报app)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 安卓大作业:使用Android Studio开发天气预报APP(使用sqlite数据库)

    今天我来分享一下如何使用Android Studio开发一个天气预报APP。在文中,我们将使用第三方接口获取实时天气数据,并显示在APP界面上。 首先,打开Android Studio并创建一个新的项目。在创建新项目时,我们需要设置项目名称、包名和支持的最低API级别。 为了获取实时天气数据,

    2024年02月08日
    浏览(27)
  • 记录--手把手教你Vue+ECharts+高德地图API实现天气预报数据可视化

    所谓数据可视化,我们可以理解为从宏观角度来看一眼就能看出来整个数据的占比,走向。对于数据可视化,很多互联网公司是很看重这一块的,包括大厂;就比如阿里的淘宝,双十一的时候往往就需要将消费者的一些数据通过图的形式展现出来。接下来我们就来实现一个天

    2024年02月07日
    浏览(31)
  • Android Studio 实现天气预报App (简单方便展示内容超多)

    🍅 文章末尾有获取完整项目源码方式 🍅 目录 前言 一、任务介绍 1.1 背景 1.2目的和意义 二、 实现介绍 视频演示 2.1 启动页实现 2.2注册页面实现 2.3 登陆页面实现 2.4 首页实现 2.5 城市管理列表页面实现                三、获取源码         在使用Android Studio开发

    2024年04月24日
    浏览(25)
  • STM32使用ESP8266模块AT指令连接心知天气API获取天气信息

    由于之前使用STM32单片机来开发一些物联网的小项目,接触到了WIFI模块ESP8266,所以写下来记录一下。 本文主要介绍的是STM32通过发送AT指令集来控制ESP8266 WIFI模块连接WiFi并与心知天气API建立TCP连接获取天气信息。 ESP8266我使用的是正点原子的ATK-ESP8266,已经提前烧录好AT指令集

    2023年04月08日
    浏览(38)
  • Android制作天气预报软件 —— 天气查询

    天气查询功能包括信息显示和地区选择两个版块,二者均通过调用极速数据的相关接口进行实现。其中,信息显示界面作为软件首页,默认先显示系统设置的地区天气情况,用户可通过地区选择的界面进行修改信息。对于天气信息,受接口调用次数限制,系统设置每24小时更

    2024年02月12日
    浏览(23)
  • 【小项目】微信定时推送天气预报Github项目使用及原理介绍-包含cron、天气预报、常用api...

    一、资料链接 1、github地址 https://github.com/qq1534774766/wx-push 2、教程地址 https://blog.csdn.net/qq15347747/article/details/126521774 3、易客云API(自动发送天气) https://yikeapi.com/account/index 4、apispace-各种接口(名人名言) https://www.apispace.com/console/api?orgId=6356 5、微信公众平台 https://mp.weixin.qq.com/d

    2024年02月02日
    浏览(24)
  • 【雕爷学编程】Arduino智能家居之使用WeatherAPI.com API获取天气预报

    Arduino是一个开放源码的电子原型平台,它可以让你用简单的硬件和软件来创建各种互动的项目。Arduino的核心是一个微控制器板,它可以通过一系列的引脚来连接各种传感器、执行器、显示器等外部设备。Arduino的编程是基于C/C++语言的,你可以使用Arduino IDE(集成开发环境)来

    2024年02月03日
    浏览(28)
  • 课程设计 天气预报数据可视化开发

    问题需求分析 数据可视化开发是指将数据呈现为漂亮的统计图表,然后进一步发现数据中包含的规律以及隐藏的信息。数据可视化开发跟数据挖掘和大数据分析紧密相关,这些领域以及当下被热议的“深度学习”其最终的目标都是为了实现从过去的数据去对未来的状况进行分

    2024年02月09日
    浏览(32)
  • 【QT开发专题-天气预报】16.更新 UI 界面

    本专栏将会在未来 4 个月内,完成以下几个 Qt 项目: 《天气预报》 《文本编辑器》 《俄罗斯方块》 《绘图板》 《网络聊天室》 《串口助手》 完成时间预计在 2022-12-31 ,文章数目在 50 篇左右,更新完毕之后,价格恢复到 ¥299 专栏优势: 每个项目都是从零新建工程开始

    2023年04月08日
    浏览(32)
  • 微信小程序实战项目开发(天气预报项目实战):内涵开发说明文档、需求文档 && 手把手分步骤教你写出自己的小程序项目 && 天气预报小程序 && 时实请求获取天气 && 自定义功能 && 完整的源代码

    微信小程序开发实现天气预报 需求分析 静态页面设计 :要求界面美观 → 在wxss代码文件中对 wxml代码文件进行合理布局和美化,舒适的交互效果. 功能逻辑完善 :能够使用到 wx.request 请求接口实现天气预报查询的功能 主要使用到的技术栈如下: wxml:中使用了 picker 组件标签

    2024年02月02日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包