相信很多人在刚接触Android时都会做一个天气预报来了解Android,今天得空整理了一个简单Android天气预报Demo的制作,如下:


首先我们应该做的便是搞到一个天气预报的API以此来获取一个Android天气预报的数据,在这里我推荐注册和风天气个人开发者,认证时间1-3天,基本一下子就可以收到了认证成功的邮件。认证开发者后可以获得中国和海外城市的7天预报、逐3小时预报、实况天气、空气质量和生活指数,对比了一下其它家,和风真是算良心接口了,虽然我只需要实况天气这一个数据。不过读者也可以利用这个接口继续完善这个Android天气预报~~~~

和风天气API网址:https://www.heweather.com/douments/api/s6/weather-forecast
<https://www.heweather.com/douments/api/s6/weather-forecast> 
各位看官可以去里面注册获得key就可以继续开发天气预报啦

1、配置参数

        既然涉及到了网络请求,肯定应该想到的时权限所以我们先添加个权限,在AndroidManifest中添加
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
        然后我这里使用的是okhttp所以添加okhttp的依赖,在app下的build.gradle中的dependencies下添加
 compile 'com.squareup.okhttp3:okhttp:3.6.0'
2、好了,该配置的都配置完了。我们接下来就制作布局吧。布局我就截个图大家可以自由制作

         

3、制作完布局后,我们就继续回到Java代码中首先先初始化各种控件这个就不过多说明

         

4、接下来开始请求接口了,这里我是个按钮添加的点击事件然后调用的search方法如下:
public void search() { Log.d(TAG, "search: 1111"); OkHttpClient client = new
OkHttpClient(); String uri =
"https://free-api.heweather.com/s6/weather?location=" +
cityItem.getSelectedItem().toString() + "&key=你在和风天气上申请的key"; Request request =
new Request.Builder() .url(uri) .build(); final Call call =
client.newCall(request); new Thread(new Runnable() { @Override public void
run() { Log.d(TAG, "run: 222222"); call.enqueue(new Callback() { @Override
public void onFailure(Call call, IOException e) { Log.d(TAG, "onResponse: " +
e); } @Override public void onResponse(Call call, Response response) throws
IOException { Message message=new Message(); message.what=1;
message.obj=response.body().string(); handler.sendMessage(message); } }); }
}).start(); }
       
这里我们是先将城市和key拼接一个GET请求,然后封装至okhttp的Call中开启线程去请求,大家千万要注意Android的禁忌那就是不能在子线程更新UI,这个是千万不能去碰的,所以我这里使用了handler的方法回到主线程更新UI。

5、handler的使用,首先我们需要创建一个全局的handler来接受子线程或其他地方传来的消息
private Handler handler = new Handler() { @Override public void
handleMessage(Message msg) { if (msg.what==1){ String
result=msg.obj.toString(); updateUI(result); Log.d(TAG, "handleMessage:
"+result); } } };
 这里面的msg.what==1就是一个标识符,代表你从哪传来的我们在请求成功后就发送消息,上面代码子线程中便有写到,如下:

          

 
 先制作一个Message消息然后将接口请求后的数据放入message中发出,我们就可以在之前定义的全局handler中去处理这个结果,在里面调用更新UI的方法。

6、更新UI,我们先来看一下天气预报接口返回的数据吧

        

     
 他这里返回的JSON是一层套一层,不过我们不要着急,一步一步的来解析,在这个项目中我使用的是Android自带的json工具来解析的,好了,我们继续。我们就已拿
"now" 现在的数据举例吧。

      首先我们看到最外层的 "HeWeather6" ,它的后面是一个 [
] 包含的数据,所以我们可以得知他是一个JSONArray于是外面我们先使用Android的JSONArray来获取它里面的数据
JSONArray jsonArray=new JSONObject(result).getJSONArray("HeWeather6");
      我们进去之后呢就看到了一个 {
} 的符号将所有数据都包揽起来了这就代表了只是一个JSONObject,我们再来用刚刚获取到的jsonarray来获取这个JSONObject,如下:
JSONObject jsonObject=jsonArray.getJSONObject(0);
      好了现在我们已经到很里面了,可以看到都是一个 " "加 { } 的结构这代表这他们都是有名字的JSONObject,我们继续来获取我们想要的
"now" 
JSONObject now=jsonObject.getJSONObject("now");
     OK,我们已经获取到了,接下来就把它里面的一个个数据放到页面中吧。更新UI的详细方法如下:
public void updateUI(String result){ try { SimpleDateFormat
simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
timeText.setText(simpleDateFormat.format(new Date())); JSONArray jsonArray=new
JSONObject(result).getJSONArray("HeWeather6"); JSONObject
jsonObject=jsonArray.getJSONObject(0); JSONObject
now=jsonObject.getJSONObject("now");
cityText.setText(cityItem.getSelectedItem().toString());
nowWeather.setText(now.get("cond_txt")+""); nowTmp.setText(now.get("tmp")+"℃");
nowWindDir.setText(now.get("wind_dir")+"");
nowWindSc.setText(now.get("wind_sc")+"级"); JSONArray
jsonArray1=jsonObject.getJSONArray("daily_forecast"); JSONObject todayJson=
(JSONObject) jsonArray1.get(0);
tmpMaxText.setText(todayJson.get("tmp_max")+"℃");
tmpMinText.setText(todayJson.get("tmp_min")+"℃");
dayTimeText.setText(todayJson.get("cond_txt_d")+"");
nightText.setText(todayJson.get("cond_txt_n")+"");
windDirText.setText(todayJson.get("wind_dir")+"");
windScText.setText(todayJson.get("wind_sc")+"级"); JSONObject tomorrowJson=
(JSONObject) jsonArray1.get(1);
tomorrowTmpText.setText(tomorrowJson.get("cond_txt_d")+"");
tomorrowCondText.setText(tomorrowJson.get("tmp_min")+"-"+tomorrowJson.get("tmp_max")+"℃");
Log.d(TAG, "updateUI: "+todayJson); Log.d(TAG, "updateUI: "+jsonArray);
Log.d(TAG, "updateUI: "+now); } catch (JSONException e) { e.printStackTrace(); }
   到这里我们这个Android天气预报就已经全部完成了,大家有什么不懂的可以留言,我会及时回复的。最后将源码放上,以供大家参考。
Android天气预报Demo源码 <https://download.csdn.net/download/q376794191/10845765>

 

       

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信