Android项目之天气预报 的实现分析

本文介绍了一款基于Android平台的天气预报应用开发过程。通过聚合数据API获取天气信息,并使用ListView展示未来七天的天气状况,包括天气、温度等详细信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android项目之天气预报 的实现分析


输入要查询的城市名称,点击查询按钮后,依次出现七天的天气情况。出现时有动画效果
二、实现过程
(一)获取天气预报数据
1、首先搞定天气预报数据来源的问题,提高天气预报服务的有很多网站,这些网站一般都会提供比较详细的 API 接口供应用程序调用,以聚合数据为例,其官网为:https://www.juhe.cn/如下图所示:


点击注册,进入注册界面:

登录成功后,就会进入到如下界面。


点击左侧菜单中我的数据,进入如下界面

点击申请新数据,如下所示,必须实名认证




进入聚合数据首页,选择 API 选项卡,选择免费的天气预报 API

点击进入后,只要申请就送 500 次使用,如下图所示。

复制其中的 AppKey:ab9d7e2007472d723baf71fcdc4ba094

打开全国天气预报 API 后,会有一项请求示例,按照其规则拼接字符串后在地址栏中输入
后可得



具体参照聚合数据的文档


下面是类的展示


2、编写网络数据访问工具类
首先需要在 uiti 包下定义一个接口,比如将它命名成 HttpCallbackListener,代码如下
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.example.weather.util;  
  2.   
  3. public interface HttpCallbackListener {  
  4.     void onFinish(String response);  
  5.     void onError(Exception e);  
  6. }  
然后定义 HttpUtil 类,代码如下
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.example.weather.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import android.util.Log;  
  10.   
  11. public class HttpUtil {  
  12.     public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {  
  13.         new Thread(new Runnable() {  
  14.             public void run() {  
  15.                 HttpURLConnection connection = null;  
  16.                 try {  
  17.                     URL url = new URL(address);  
  18.                     connection = (HttpURLConnection) url.openConnection();  
  19.                     connection.setRequestMethod("GET");  
  20.                     connection.setConnectTimeout(8000);  
  21.                     connection.setReadTimeout(8000);  
  22.                     connection.setDoInput(true);  
  23.                     connection.setDoOutput(true);  
  24.                     InputStream in = connection.getInputStream();  
  25.                     BufferedReader reader =  
  26.                             new BufferedReader(new InputStreamReader(in));  
  27.                     StringBuilder response = new StringBuilder();  
  28.                     String line;  
  29.                     while ((line = reader.readLine()) != null) {  
  30.                         response.append(line);        
  31.                     }  
  32.                     if (listener != null) {  
  33.                         // 回调 onFinish()方法  
  34.                         listener.onFinish(response.toString());  
  35.                     }  
  36.                 } catch (Exception e) {  
  37.                     if (listener != null) {  
  38.                         // 回调 onError()方法  
  39.                         listener.onError(e);  
  40.                     }  
  41.                 } finally {  
  42.                     if (connection != null) {  
  43.                         connection.disconnect();  
  44.                     }  
  45.                 }  
  46.             }  
  47.         }).start();  
  48.     }  
  49. }  
3、测试一下能否正常访问天气预报接口得到返回的数据
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.example.weather.test;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.net.URLEncoder;  
  5.   
  6. import com.example.weather.util.HttpCallbackListener;  
  7. import com.example.weather.util.HttpUtil;  
  8.   
  9. import android.test.AndroidTestCase;  
  10.   
  11. public class WeatherGetTest  extends AndroidTestCase{  
  12.      public void testGetData(){    
  13.          String cityName;  
  14.         try {  
  15.             cityName = URLEncoder.encode("菏泽""utf-8");  
  16.             String  weatherUrl="http://v.juhe.cn/weather/index?format=2&cityname="+cityName+"&key=ab9d7e2007472d723baf71fcdc4ba094";  
  17.           
  18.          HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {  
  19.               
  20.             public void onFinish(String response) {  
  21.                 // TODO Auto-generated method stub  
  22.                 System.out.println(response);  
  23.             }  
  24.               
  25.             public void onError(Exception e) {  
  26.                 // TODO Auto-generated method stub  
  27.                   
  28.             }  
  29.             });  
  30.          }catch (Exception e) {  
  31.             // TODO: handle exception  
  32.         }  
  33.       
  34.      }  
  35. }  

由于涉及到访问网络,需要在 AndroidManifest.xml 文件中加入访问网络的权限。
<uses-permission android:name="android.permisson.Internet"/>


(三)UI 设计
activity_weather.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@drawable/city"  
  6.     tools:context=".WeatherActivity" >  
  7.   
  8.     <LinearLayout  
  9.         android:id="@+id/linearLayout1"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:orientation="horizontal" >  
  13.   
  14.         <EditText  
  15.             android:id="@+id/etCity"  
  16.             android:layout_width="0dp"  
  17.             android:layout_height="wrap_content"  
  18.             android:layout_marginLeft="10dp"  
  19.             android:layout_marginTop="20dp"  
  20.             android:layout_weight="1"  
  21.             android:background="@android:drawable/edit_text"  
  22.             android:drawableLeft="@drawable/etcity"  
  23.             android:drawablePadding="5dp"  
  24.             android:ems="10"  
  25.             android:hint="@string/etCity" >  
  26.   
  27.             <requestFocus />  
  28.         </EditText>  
  29.   
  30.         <ImageButton  
  31.             android:id="@+id/btnQuery"  
  32.             android:layout_width="50dp"  
  33.             android:layout_height="50dp"  
  34.             android:layout_marginTop="20dp"        
  35.             android:background="@null"  
  36.             android:src="@drawable/serch" />  
  37.     </LinearLayout>  
  38.   
  39.     <ListView  
  40.         android:id="@+id/lvFutureWeather"  
  41.         android:layout_width="match_parent"  
  42.         android:layout_height="wrap_content"  
  43.         android:layout_below="@+id/linearLayout1"  
  44.         android:layout_centerHorizontal="true"  
  45.         android:layout_marginLeft="10dp"  
  46.         android:layout_marginRight="10dp"  
  47.         android:dividerHeight="10dp"  
  48.         android:layoutAnimation="@anim/weather_list_layout_animation" >  
  49.     </ListView>  
  50.   
  51. <span style="color:#ff0000;"></RelativeLayout></span>  
activity_weather_listitem.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:layout_margin="10dp"  
  6.     android:background="@drawable/list_item_shape"  
  7.     android:padding="10dp" >  
  8.   
  9.     <TextView  
  10.         android:id="@+id/tvDayofWeek"  
  11.         android:layout_width="wrap_content"  
  12.         android:layout_height="wrap_content"  
  13.         android:layout_alignParentLeft="true"  
  14.         android:layout_alignParentTop="true"  
  15.         android:layout_marginLeft="15dp"  
  16.         android:text="星期日" />  
  17.   
  18.     <TextView  
  19.         android:id="@+id/tvDate"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:layout_alignBaseline="@+id/tvDayofWeek"  
  23.         android:layout_alignBottom="@+id/tvDayofWeek"  
  24.         android:layout_alignParentRight="true"  
  25.         android:text="20160207" />  
  26.   
  27.     <TextView  
  28.         android:id="@+id/tvTemperature"  
  29.         android:layout_width="wrap_content"  
  30.         android:layout_height="wrap_content"  
  31.         android:layout_alignLeft="@+id/tvDayofWeek"  
  32.         android:layout_below="@+id/tvDayofWeek"  
  33.         android:layout_marginTop="15dp"  
  34.         android:text="temperature" />  
  35.   
  36.     <TextView  
  37.         android:id="@+id/tvWeather"  
  38.         android:layout_width="wrap_content"  
  39.         android:layout_height="wrap_content"  
  40.         android:layout_alignLeft="@+id/tvTemperature"  
  41.         android:layout_below="@+id/tvTemperature"  
  42.         android:layout_marginTop="15dp"  
  43.         android:text="weather" />  
  44.   
  45. </RelativeLayout>  

其中 weather_list_layout_animation.xml 文件是一个设置布局动画的,实现过程如下 :
在 res 目录下新建 anim 文件夹, 在其下新建 weather_list_layout_animation.xml 文件, 如下:
weather_list_animation.xml
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <set xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.   
  4.     <scale  
  5.         android:duration="1000"  
  6.         android:fromXScale="0.0"  
  7.         android:fromYScale="0.0"  
  8.         android:interpolator="@android:anim/accelerate_decelerate_interpolator"  
  9.         android:toXScale="1.0"  
  10.         android:toYScale="1.0" />  
  11.   
  12. </set>  
weather_list_layout_animation.xml
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>  
  2. <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:animation="@anim/weather_list_animation"  
  4.     android:animationOrder="normal"  
  5.     android:delay="2" /></span>  

Weather.java
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.example.weather.moder;  
  2.   
  3. public class Weather {  
  4.     private String dayOfWeek;//星期几  
  5.     private String date;//日期  
  6.     private String temperature;//温度  
  7.     private String weather;//天气  
  8.     public Weather(){  
  9.     }  
  10.     public Weather(String dayOfWeek, String date, String temperature,  
  11.             String weather) {  
  12.         super();  
  13.         this.dayOfWeek = dayOfWeek;  
  14.         this.date = date;  
  15.         this.temperature = temperature;  
  16.         this.weather = weather;  
  17.     }  
  18.     public String getDayOfWeek() {  
  19.         return dayOfWeek;  
  20.     }  
  21.     public void setDayOfWeek(String dayOfWeek) {  
  22.         this.dayOfWeek = dayOfWeek;  
  23.     }  
  24.     public String getDate() {  
  25.         return date;  
  26.     }  
  27.     public void setDate(String date) {  
  28.         this.date = date;  
  29.     }  
  30.     public String getTemperature() {  
  31.         return temperature;  
  32.     }  
  33.     public void setTemperature(String temperature) {  
  34.         this.temperature = temperature;  
  35.     }  
  36.     public String getWeather() {  
  37.         return weather;  
  38.     }  
  39.     public void setWeather(String weather) {  
  40.         this.weather = weather;  
  41.     }  
  42.     @Override  
  43.     public String toString() {  
  44.         return "Weather [dayOfWeek=" + dayOfWeek + ", date=" + date  
  45.                 + ", temperature=" + temperature + ", weather=" + weather + "]";  
  46.     }  
  47.   
  48. }  
在 adapter 包下定义适配器 WeatherAdapter
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.example.weather.adapter;  
  2.   
  3.   
  4. import java.util.List;  
  5.   
  6. import android.content.Context;  
  7. import android.view.LayoutInflater;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.widget.ArrayAdapter;  
  11. import android.widget.TextView;  
  12.   
  13. import com.example.weather.R;  
  14. import com.example.weather.moder.Weather;  
  15.   
  16. /** 
  17.  * 天气适配器 
  18.  * @author zhupeng 
  19.  * 
  20.  */  
  21. public class WeatherAdapter extends ArrayAdapter<Weather> {  
  22.     private int resourceId;  
  23.     public WeatherAdapter(Context context, int textViewResourceId,  
  24.             List<Weather> objects) {  
  25.         super(context, textViewResourceId, objects);  
  26.         resourceId = textViewResourceId;  
  27.     }  
  28.     @Override  
  29.     public View getView(int position, View convertView, ViewGroup viewgroup) {  
  30.         Weather weather=getItem(position);  
  31.         ViewHolder viewHolder=null;  
  32.         if(convertView==null){  
  33.             viewHolder=new ViewHolder();  
  34.             convertView=LayoutInflater.from(getContext()).inflate(resourceId, null);  
  35.             viewHolder.tvDayOfWeek=(TextView)  
  36.                     convertView.findViewById(R.id.tvDayofWeek);  
  37.             viewHolder.tvDate=(TextView) convertView.findViewById(R.id.tvDate);  
  38.             viewHolder.tvTemperature=(TextView) convertView.findViewById(R.id.tvTemperature);  
  39.             viewHolder.tvWeather=(TextView) convertView.findViewById(R.id.tvWeather);  
  40.             convertView.setTag(viewHolder);  
  41.         }else{  
  42.             viewHolder=(ViewHolder) convertView.getTag();  
  43.         }  
  44.         viewHolder.tvDayOfWeek.setText(weather.getDayOfWeek());  
  45.         viewHolder.tvDate.setText(weather.getDate());  
  46.         viewHolder.tvTemperature.setText(weather.getTemperature());  
  47.         viewHolder.tvWeather.setText(weather.getWeather());  
  48.         return convertView;  
  49.     }  
  50.     private class ViewHolder{  
  51.         TextView tvDayOfWeek;  
  52.         TextView tvDate;  
  53.         TextView tvTemperature;  
  54.         TextView tvWeather;  
  55.     }  
  56. }  
WeatherActivity.java
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">package com.example.weather;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.net.URLEncoder;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import com.example.weather.adapter.WeatherAdapter;  
  9. import com.example.weather.moder.Weather;  
  10. import com.example.weather.util.HttpCallbackListener;  
  11. import com.example.weather.util.HttpUtil;  
  12. import com.google.gson.JsonArray;  
  13. import com.google.gson.JsonObject;  
  14. import com.google.gson.JsonParser;  
  15.   
  16. import android.app.Activity;  
  17. import android.os.Bundle;  
  18. import android.os.Handler;  
  19. import android.os.Message;  
  20. import android.view.View;  
  21. import android.view.View.OnClickListener;  
  22. import android.view.animation.LayoutAnimationController;  
  23. import android.view.animation.ScaleAnimation;  
  24. import android.widget.EditText;  
  25. import android.widget.ImageButton;  
  26. import android.widget.ListView;  
  27. import android.widget.Toast;  
  28. public class WeatherActivity extends Activity {  
  29.     private EditText ecCity;  
  30.     private ImageButton btnQuery;  
  31.     private ListView lvFutureWeather;  
  32.     public static final int SHOW_RESPONSE=1;  
  33.     private List<Weather> data;  
  34.     private Handler handler=new Handler(){  
  35.         public void handleMessage(Message msg){  
  36.             switch (msg.what) {  
  37.             case SHOW_RESPONSE:  
  38.                 String response=(String )msg.obj;  
  39.                 if(response!=null){  
  40.                     parseWithJSON(response);  
  41.                     WeatherAdapter weatherAdapter=new WeatherAdapter  
  42.                             (WeatherActivity.this,   
  43.                                     R.layout.activity_weather_listitem, data);  
  44.                     lvFutureWeather.setAdapter(weatherAdapter);  
  45.                     ScaleAnimation scaleAnimation=new ScaleAnimation(0,1,0,1);  
  46.                     scaleAnimation.setDuration(1000);  
  47.                     LayoutAnimationController animationController  =  new  
  48.                             LayoutAnimationController(  
  49.                                     scaleAnimation, 0.6f);  
  50.                     lvFutureWeather.setLayoutAnimation(animationController);  
  51.   
  52.                 }  
  53.                 break;  
  54.   
  55.             default:  
  56.                 break;  
  57.             }  
  58.         }  
  59.   
  60.         private void parseWithJSON(String response) {  
  61.             // TODO Auto-generated method stub  
  62.             data=new ArrayList<Weather>();  
  63.             JsonParser parser=new JsonParser();//json解析器  
  64.             JsonObject obj=(JsonObject) parser.parse(response);  
  65.             //获取返回状态吗  
  66.             String resultcode=obj.get("resultcode").getAsString();  
  67.             //状态码如果是200说明数据返回成功  
  68.             if(resultcode!=null&&resultcode.equals("200")){  
  69.                 JsonObject resultObj=obj.get("result").getAsJsonObject();  
  70.                 JsonArray futureWeatherArray=resultObj.get("future").getAsJsonArray();  
  71.                 for(int i=0;i<futureWeatherArray.size();i++){  
  72.                     Weather  weather=new Weather();  
  73.                     JsonObject weatherObject=futureWeatherArray.get(i).getAsJsonObject();  
  74.                     weather.setDayOfWeek(weatherObject.get("week").getAsString());  
  75.                     weather.setDate(weatherObject.get("date").getAsString());  
  76.                     weather.setTemperature(weatherObject.get("temperature")  
  77.                             .getAsString());  
  78.                     weather.setWeather(weatherObject.get("weather")  
  79.                             .getAsString());  
  80.                     data.add(weather);  
  81.                 }  
  82.             }  
  83.         }  
  84.   
  85.     };  
  86.     @Override  
  87.     protected void onCreate(Bundle savedInstanceState) {  
  88.         super.onCreate(savedInstanceState);  
  89.         setContentView(R.layout.activity_weather);  
  90.         initViews();  
  91.         setListeners();  
  92.   
  93.     }  
  94.     public void initViews(){  
  95.         ecCity=(EditText) findViewById(R.id.etCity);  
  96.         btnQuery=(ImageButton)findViewById(R.id.btnQuery);  
  97.         lvFutureWeather=(ListView) findViewById(R.id.lvFutureWeather);  
  98.          data=new ArrayList<Weather>();  
  99.     }  
  100.     private void setListeners(){  
  101.         btnQuery.setOnClickListener(new OnClickListener() {  
  102.   
  103.             public void onClick(View v) {  
  104.                 // TODO Auto-generated method stub  
  105.                 String cityName=ecCity.getText().toString();    
  106.                 try {  
  107.                     cityName = URLEncoder.encode("菏泽""utf-8"); //这里我弄成默认的城市了,如果想根据输入的值进行搜索,,,可以把这句话换成cityName = URLEncoder.encode(cityName, "utf-8");  
  108.   
  109.   
  110.                 } catch (UnsupportedEncodingException e1) {  
  111.                     e1.printStackTrace();  
  112.                 }  
  113.                 System.out.println("lvFutureWeather="+lvFutureWeather);  
  114.                 Toast.makeText(WeatherActivity.this"success",  
  115.                         Toast.LENGTH_LONG).show();  
  116.                 String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="+cityName+"&key=ab9d7e2007472d723baf71fcdc4ba094";  
  117.                 Toast.makeText(WeatherActivity.this"success"+weatherUrl,  
  118.                         Toast.LENGTH_LONG).show();  
  119.                 HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {  
  120.   
  121.                     public void onFinish(String response) {  
  122.                         // TODO Auto-generated method stub  
  123.                         Message message=new Message();  
  124.                         message.what=SHOW_RESPONSE;  
  125.                         //将服务器返回的结果存放到Message中  
  126.                         message.obj=response.toString();  
  127.                         handler.sendMessage(message);  
  128.                     }  
  129.   
  130.                     public void onError(Exception e) {  
  131.                         // TODO Auto-generated method stub  
  132.                         System.out.println("访问失败");  
  133.                     }  
  134.                 });  
  135.             }  
  136.         });  
  137.     }  
  138.   
  139. }</span><strong>  
  140. </strong>  

注意:  在进行查询输入城市名时一定要先改编码格式  列如
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">cityName = URLEncoder.encode("菏泽""utf-8");</span>  

源码http://pan.baidu.com/s/1boGVBtl    密码 nmge

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值