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


一、环境配置和素材准备

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

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

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

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

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

添加第三方依赖okhttp:

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

二、代码讲解

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

  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() {@Overridepublic 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(){@Overridepublic 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()]);}}};

最终效果:

三、完整代码

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(){@Overridepublic 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()]);}}};@Overrideprotected 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() {@Overridepublic void onClick(View v) {sendHttpRequest();Toast.makeText(MainActivity.this,"11",Toast.LENGTH_LONG).show();}
});}public void sendHttpRequest() {new Thread(new Runnable() {@Overridepublic 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"><LinearLayoutandroid: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"><TextViewandroid: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="实况" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="72dp"android:orientation="horizontal"><EditTextandroid: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="" /><Buttonandroid: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><TextViewandroid: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><ImageViewandroid:id="@+id/iv1"android:layout_width="match_parent"android:layout_height="381dp"></ImageView><TextViewandroid: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)相关推荐

  1. 心知天气api接口怎么用?

    心知天气是什么?心知天气提供API吗? 心知天气是国内领先的气象服务商,由中国气象局官方授权的商业气象服务公司,基于气象数值预报和人工智能技术,提供高精度气象数据.天气监控机器人.气象数据可视化产品, ...

  2. 心知天气api,根据城市名/id查询天气

    心知天气api可以根据城市名/id查询天气,向开发者提供的准确.稳定.丰富的天气数据云服务. 接口名称:心知天气api 接口平台:聚合数据 接口地址:http://v.juhe.cn/weather/ ...

  3. STM32使用ESP8266模块AT指令连接心知天气API获取天气信息

    由于之前使用STM32单片机来开发一些物联网的小项目,接触到了WIFI模块ESP8266,所以写下来记录一下.本文主要介绍的是STM32通过发送AT指令集来控制ESP8266 WIFI模块连接WiFi ...

  4. Android中基于心知天气API获取天气信息

    Android中基于心知天气获取天气信息 JSON JSON简介 JSON对象 JSON数组 JSON解析 Android中获取天气 获取天气的流程 获取心知天气的API key 获取心知天气的API ...

  5. 心知天气API如何调用与json数据如何显示

    心知天气官网:https://www.seniverse.com/doc 首先需要注册获得密钥和ID. 因为我不是会员,这里就简单介绍下,怎么调用并显示. Json数据如下图所示: { results ...

  6. c语言获取天气信息示例(通过心知天气api获取)

    关于curl/curl.h库的使用,参考下述内容: VS2010编译libcurl库并简单使用(c语言)_西晋的no1的博客-CSDN博客 1.先在心知天气注册,获取私钥:  https://www. ...

  7. 利用Arduino Esp8266 心知天气API 获取天气预报信息(修改后可以DIY一个小型的桌面气象台)

    前期准备: 注册心知天气,获取API密钥  https://www.seniverse.com 生成API请求地址,北京今天和未来4天的预报请求地址如下: https://api.seniverse. ...

  8. Spring Boot项目:使用第三方天气API接口实现天气预报功能

    查询天气的api:"http://aider.meizu.com/app/weather/listWeather?cityIds=101210101" 直接在city=后面加上中文 ...

  9. php中国天气api接口,免费天气预报API接口使用教程(信息来源权威及时)

    本文将介绍两种免费获取天气预报信息的方式(天气信息来源于国家气象局,还是比较权威及时的): (1)JSON 类型接口: JSON 类型的接口返回的数据又有三种形式,具体各种接口地址以及返回信息形式参见 ...

最新文章

  1. postfilter中文什么意思_Filterpost请求中文字符编码的过滤器 --学习笔记
  2. GP官网上的TEE学习课程和费用介绍
  3. 用java实现zip压缩
  4. kafka 串讲:架构模型、角色功能梳理
  5. input数字开头不能为0_李商隐为初恋写诗,每句以数字开头,最后10字一直被仿从未被超越...
  6. matlab fminimax 例子,Matlab应用实例(8)—fminimax
  7. cas4.2.7与shiro进行整合
  8. (26)VHDL实现或(数据流描述)
  9. 【学习率调整】学习率衰减之周期余弦退火 (cyclic cosine annealing learning rate schedule)
  10. 小白使用ansible
  11. Code Review 13 大必知必会,学习了!
  12. text-transform 文本大小写转换、input checkbok 大小设置、letter-spacing 设置字符间距
  13. 笑死人了,要抑制房价的过快上涨?
  14. 完整的vue-cli3项目创建过程以及各种配置
  15. 数据结构课程设计 # 论文查重分析系统 (C/C++版和python版)
  16. jQuery菜鸟教程04
  17. 蝴蝶效应、青蛙现象、鳄鱼法则
  18. A Complete ActiveX Web Control Tutorial
  19. 2017 BIT复试机试(软件)
  20. Leetcode 1345 跳跃游戏 IV

热门文章

  1. Java 利用http协议与Domino实现sso单点登录
  2. Python爬虫笔记——Ajax简介
  3. ThinkPHP 整合微信支付 扫码支付 模式二 图文教程
  4. C语言:写个程序把给定的符号打印成沙漏的形状。
  5. php出现NaN,【整理】PHP中的NaN是什么意思
  6. 把Java的nio坑逐个踩一遍
  7. 梯度流是个什么玩意儿
  8. Linux下,支付宝安全控件失效,解决方法
  9. Excel如何给学生成绩排名
  10. Windows10安装.NET Framework3.5时失败的解决