IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android实现-知心天气API接口开发(天气预报app) -> 正文阅读

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

自己开发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() {
            @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()]);
            }
        }
    };

最终效果:

?

三、完整代码

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>

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-10-22 21:26:57  更:2022-10-22 21:30:14 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/20 0:18:45-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码