android天气预报源代码解析
- 格式:doc
- 大小:124.50 KB
- 文档页数:24
Android 谷歌天气预报该项目是东方标准广州java培训中心为java技术开发学习人员和android技术开发班的学员共同开发研制的一款生活助手软件《谷歌天气预报》。
项目来自于日常生活中天气预报新闻。
由于人们日益紧凑的生活节奏,对于天气的关注不如以前那么重要,所以为了节省人们的业余时间,直接将天气预报功能搬入了手机软件功能当中,方便人们阅读浏览当地天气情况,并适当做出生活调整。
该项目技术要点为:推送功能+后台服务设计Service+联网功能HTTP+xml解析器XmlPullParser等技术。
一.项目介绍《谷歌天气预报》是一款简单的天气预报定制软件。
界面简洁易懂,方便用户使用。
可以查询几大城市的天气预报情况,主要功能有天气预告、城市温度、湿度、未来几天天气预测等。
该软件使用起来非常方便。
只要输入所查看的城市,软件自动提供当地的天气情况,以供查询。
二.For personal use only in study and research; not for commercial use三.四.功能说明1、进入软件页面2、功能说明1)、【天气】功能:显示当前天气情况。
资料来自于互联网真实天气预报。
2)、【城市】功能:显示当前所在城市。
3)、【温度】功能:显示选择城市天气温度变化。
资料来自互联网真实天气温度预告。
4)、【湿度】功能:显示当地城市湿度5)、【天气预测】功能:预测未来几天的天气状况。
可以预测未来三天以内的天气资料。
6)、【更新日期】功能: 显示当前天气日期。
五.程序设计技术说明本程序主要使用Service服务。
Android开发中,当需要创建在后台运行的程序的时候,就要使用到Service。
Service 可以分为有无限生命和有限生命两种。
特别需要注意的是Service跟Activities是不同的(简单来说可以理解为后台与前台的区别),例如,如果需要使用Service的话,需要调用startService(),从而利用 startService()去调用Service中的OnCreate()和onStart()方法来启动一个后台的Service。
基于AndroidStudio的天气预报APP设计与实现基于Android Studio的天气预报APP设计与实现一、引言随着智能手机的普及,人们对天气预报的需求也越来越大。
天气预报APP作为一种重要的生活辅助工具,对于雨天出行、户外活动的安排、衣物搭配等方面都有着重要的作用。
本文将介绍基于Android Studio的天气预报APP的设计与实现。
二、需求分析在开发天气预报APP之前,首先需要对用户需求进行分析。
根据市场研究,用户对于天气预报APP的需求主要有以下几个方面:1. 准确的天气预报信息:用户希望获取当前和未来几天的天气情况,包括温度、湿度、风力等信息;2. 实时更新:用户希望天气信息能够实时更新,使其能够及时了解最新的天气状况;3. 用户体验:用户希望使用简单、操作流畅的APP,同时能够个性化设置,例如添加多个城市、查看不同地区的天气情况等;4. 数据来源:用户对天气数据的来源也有要求,希望能够信任数据来源,确保数据的准确性。
三、系统设计基于以上需求,设计并实现一个功能完善的天气预报APP需要考虑以下几个方面:1. 用户界面设计:设计一个直观、美观的用户界面,可以通过页面的布局和色彩搭配来提升用户体验;2. 天气数据接口:选择可信赖的天气数据接口,可以通过与数据接口提供商合作来获取天气数据,确保数据的实时性和准确性;3. 数据存储:设计一个数据库来存储用户的设置信息,包括添加的城市、个性化设置等,使用户在下次打开APP时能够恢复之前的设置;4. 数据更新机制:设计一个数据更新机制,自动更新天气数据,并提供手动更新功能,确保用户获取到最新的天气信息;5. 用户交互设计:设计一个简单、易用的用户交互界面,可以通过点击、滑动等操作来获取和切换城市的天气信息;6. 错误处理:考虑到天气数据接口可能出现异常,需要设计相应的错误处理机制,例如网络异常时给出提示信息或者使用缓存数据。
四、技术实现基于Android Studio进行天气预报APP的开发,可以利用Android Studio提供的图形化界面设计工具和代码编辑器进行开发,主要技术有以下几个方面:1. 使用Android SDK提供的API获取用户当前的地理位置信息;2. 通过HTTP请求获取天气数据,并解析JSON格式的数据;3. 使用SQLite数据库进行数据存储,保存用户的设置信息;4. 使用多线程技术实现数据的异步更新,避免主线程阻塞;5. 使用Android Studio的UI设计工具进行界面布局和样式设置;6. 进行错误处理,例如网络异常时给出用户友好的提示信息。
Android 天气预报程序开发实例与定位信息昨天我们大概描述了下Android 中的XML 解析,其实整个实现方式比较简单,可以参考 的例子和monsware.android.internet 例子,Google Weather API 还包含了另一种方式根据经度、纬度方式获取天气信息。
在T-Mobile G1中可以通过基于移动网络和GPS 方式定位,粗略获取当前定位坐标可以下面代码获取。
1 2 3 4 LocationManager myLocationManager=null ;myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SER VICE);Location l = myLocationManager.getLastKnownLocation("network");//这里使用myLocation 方式获取。
String url = l.getLatitude() +","+ l.getLongitude();//这里获取到了精度和维度即使不用GPS 我们基本上可以获取粗略的城市位置。
这里获取的l.getLatitude()返回的是浮点型,我们需要处理下,比如获取的为31.174165,需要过滤掉“.”保留31174165即可,维度同理:我们提交下面的/ig/api?weather=,,,31174165,121433841 数据即可获取,这里我们使用了Google Weather API 的精度维度方式获取,根据城市拼音名可以参考昨天的Android 与XML 解析一文,获取的内容如下:即使不用GPS 我们基本上可以获取粗略的城市位置。
这里获取的l.getLatitude()返回的是浮点型,我们需要处理下,比如获取的为31.174165,需要过滤掉“.”保留31174165即可,维度同理:我们提交下面的/ig/api?weather=,,,31174165,121433841 数据即可获取,这里我们使用了Google Weather API 的精度维度方式获取,根据城市拼音名可以参考昨天的Android 与XML 解析一文,获取的内容如下:1 2 3 4 5 6 7 8 9 <?xml version="1.0"?><xml_api_reply version="1"><weather module_id="0"tab_id="0"><forecast_information><city data=""/><postal_code data=""/><latitude_e6 data="31174165"/><longitude_e6 data="121433841"/>10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31<forecast_date data="2008-12-18"/><current_date_time data="2008-12-18 18:00:00 +0000"/><unit_system data="SI"/></forecast_information><current_conditions><condition data="晴"/><temp_f data="52"/><temp_c data="11"/><humidity data="湿度: 44%"/><icon data="/images/weather/sunny.gif"/><wind_condition data="风向: 北、风速:14 (公里/小时)"/></current_conditions><forecast_conditions><day_of_week data="周四"/><low data="4"/><high data="12"/><icon data="/images/weather/sunny.gif"/><condition data="晴"/></forecast_conditions><forecast_conditions><day_of_week data="周五"/><low data="7"/><high data="15"/><icon data="/images/weather/mostly_sunny.gif"/><condition data="以晴为主"/></forecast_conditions><forecast_conditions><day_of_week data="周六"/><low data="4"/><high data="16"/><icon data="/images/weather/sunny.gif"/><condition data="晴"/></forecast_conditions><forecast_conditions><day_of_week data="周日"/><low data="-6"/><high data="5"/><icon data="/images/weather/cn_cloudy.gif"/><condition data="多云"/></forecast_conditions></weather></xml_api_reply>32333435363738394414243444546474849551最后,不要忘了加入定位相关的permission,这里还有一些细节问题,比如摄氏度和华氏度的转换以及时区问题。
项⽬源码--Android天⽓⽇历精致UI源码
技术要点:
1. 天⽓⽇历精致UI
2. Android的Http通信技术
3. Android的天⽓信息解析
4. Android的⽇历信息的统计
5. Andorid的地理位置的管理
6.源码带有⾮常详细的中⽂注释
……
详细介绍:
1. 天⽓⽇历精致UI
此套源码的UI不错,⽐较精致。
实现了天⽓信息的合理显⽰,位置的管理以及⽇历信息的显⽰
2.Android的Http通信技术
通过Http通信技术与服务器进⾏通信,动态的更新指定位置天⽓信息
3.Android的天⽓信息解析
针对服务器返回的天⽓信息数据,客户端进⾏解析,正确的显⽰指定地⽅的天⽓信息
4. ⽇历信息的统计
根据⽇历的统计算法,提供了⽇历的信息显⽰与管理
5. Andorid的地理位置的管理
实现了地理位置的显⽰,可通过更新地理位置,从⽽显⽰当前位置的天⽓信息
6. 项⽬源码⽬录
运⾏效果:。
编写简易Android天⽓应⽤的代码⽰例本⽂所要介绍的简易天⽓App主要⽤RxAndroid、MVP、Retrofit实现,⾸先来看看效果:主页内容:右侧栏天⽓列表:左侧栏城市列表⾸先看看Activity主要代码(使⽤MVP模式)://调⽤Presenter的⽅法获取数据mMainPresenter = new MainPresenterImpl(this);mMainPresenter.getPlaceData();mMainPresenter.getWeatherData("成都");//显⽰主页和右侧栏天⽓数据public void setupWeatherData(WeatherResponse weatherResponse) {if (weatherResponse == null) return;setTitleText(DateUtils.getWeekDay(weatherResponse.date));if (weatherResponse.results != null && weatherResponse.results.size() > 0) {WeatherResult result = weatherResponse.results.get(0);mTvCity.setText(getString(R.string.city, result.currentCity));mTvPm25.setText(getString(R.string.pm25, result.pm25));mWeatherDataAdapter.setData(result.weather_data);mWeatherDataAdapter.notifyDataSetChanged();mWeatherExtraAdapter.setData(result.index);mWeatherExtraAdapter.notifyDataSetChanged();}}//显⽰左侧栏城市列表@Overridepublic void setupPlaceData(List<Place> placeList) {if (placeList == null) {return;}mPlaceAdapter.setData(placeList);mPlaceAdapter.notifyDataSetChanged();}接下来看看如何在Presenter中应⽤RxJava、RxAndroid获取数据//获取天⽓数据@Overridepublic void getWeatherData(String place) {if (TextUtils.isEmpty(place)) {return;}mMainView.showProgress();ServiceManager.getInstance().getApiService().getWeatherInfo(place, Constants.BAIDU_AK).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<WeatherResponse>() {@Overridepublic void onCompleted() {Log.e(TAG, "onCompleted");mMainView.hideProgress();}@Overridepublic void onError(Throwable e) {Log.e(TAG, e.getMessage(), e);mMainView.hideProgress();@Overridepublic void onNext(WeatherResponse weatherResponse) {mMainView.setupWeatherData(weatherResponse);}});}public interface ApiService {/*@GET("service/getIpInfo.php")Call<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);*/@GET("service/getIpInfo.php")Observable<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);///telematics/v3/weather?location=%E6%88%90%E9%83%BD&output=json&ak=MPDgj92wUYvRmyaUdQs1XwCf@GET("/telematics/v3/weather?output=json")Observable<WeatherResponse> getWeatherInfo(@Query("location") String location, @Query("ak") String ak);}如上所述,我们通过百度api获取天⽓数据使⽤的是Retrofit框架,它能⾃动的返回Observable对象。
Android全国天气预报SDK演示示例今天要分享的是android手机设备集成天气预报功能的方案。
我采用的方案是使用聚合数据上的全国天气预报API。
如需要,可申请:实现步骤:1.到聚合数据官网上注册,然后申请申请全国天气预报SDK数据,生成AppKey。
2.配置工程,将开发包里的juhe_sdk_v_1_1.jar拷贝到libs根目录下,将libJuheSDK_v_1_0.so拷贝到libs\armeabi目录下,如图:3.根据接口说明文档找到以下方法:/*** 根据城市名查询天气** @param cityname* 城市名,如:"苏州"* @param format* 未来6天预报(future)两种返回格式,1或2,默认1** @param jsonCallBack**/public void getByCitys(String cityname, int format, JsonCallBack jsonCallBack) /*** 天气种类及标识列表** @param jsonCallBack**/public void getUni(JsonCallBack jsonCallBack) /**** 根据IP查询天气** @param ip* ip地址,如:58.215.185.154* @param format* 未来6天预报(future)两种返回格式,1或2,默认1* @param jsonCallBack**/public void getByIP(String ip, int format, JsonCallBack jsonCallBack)/**** 根据GPS坐标查询天气*** @param lon* 经度* @param lat* 纬度* @param format* 未来6天预报(future)两种返回格式,1或2,默认1* @param jsonCallBack**/public void getByGEO(double lat, double lon, int format, JsonCallBack jsonCallBack) /*** 城市天气三小时预报** @param cityname* @param jsonCallBack**/public void getForecast3h(String cityname, JsonCallBack jsonCallBack) /*** 支持城市列表** @param jsonCallBack*/public void getCities(JsonCallBack jsonCallBack)4.程序中调用方法首先,在AnroidManifest.xml中添加权限<uses-permissionandroid:name="android.permission.READ_PHONE_STATE" /> <uses-permissionandroid:name="android.permission.INTERNET" /><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permissionandroid:name="android.permission.READ_CONTACTS" />在application标签内部加入你申请的openid<meta-dataandroid:name="com.thinkland.juheapi.openid"android:value="申请的openid" />在使用前需要调用一次初始化方法CommonFun.initialize(getApplicationContext());导入相关包impimportmonFun;import mon.JsonCallBack;importcom.thinkland.juheapi.data.weather.WeatherData调用方法//根据城市名/id查询天气WeatherData weatherData = WeatherData.getInstance();weatherData.getByCitys("苏州", 1, new JsonCallBack() {@Overridepublic void jsonLoaded(JSONObject arg0) {// TODO Auto-generated method stubtry {int code = arg0.getInt("resultcode");if (code == 200) {JSONObject resultJson = arg0.getJSONObject("result");}} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});。
2-1 使用XML解析制作天气预报操作指导一、界面布局设计1.界面元素与布局分析图1 界面元素图2 界面布局2.代码需要控件的id3.布局代码<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/weather"tools:context=".MainActivity"><TextViewandroid:id="@+id/tv_city"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginBottom="20dp"android:layout_marginLeft="50dp"android:layout_marginTop="80dp"android:text="上海"android:textSize="40sp"android:textColor="#ff0505" /><ImageViewandroid:id="@+id/iv_icon"android:layout_width="120dp"android:layout_height="120dp"android:layout_alignLeft="@+id/tv_city"android:layout_below="@+id/tv_city"android:layout_marginBottom="10dp"android:layout_marginLeft="30dp"android:src="@drawable/ic_launcher" /><TextViewandroid:id="@+id/tv_weather"android:layout_width=" wrap_content "android:layout_height="wrap_content"android:layout_below="@+id/iv_icon"android:layout_alignLeft="@+id/iv_icon"android:layout_alignLeft="@+id/iv_icon"android:gravity="center"android:text="多云"android:textSize="18sp" /><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignTop="@+id/iv_icon"android:layout_marginLeft="30dp"android:layout_toRightOf="@+id/iv_icon"android:layout_marginTop="15dp"android:orientation="vertical"><TextViewandroid:id="@+id/tv_temp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginBottom="8dp"android:text="温度:28℃"android:textSize="22sp" /><TextViewandroid:id="@+id/tv_wind"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginBottom="8dp"android:text="风力:10级"android:textSize="20sp" /><TextViewandroid:id="@+id/tv_pm"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="PM:80"android:textSize="20sp" /></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"<Buttonandroid:id="@+id/btn_sh"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="上海" /><Buttonandroid:id="@+id/btn_bj"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="北京" /><Buttonandroid:id="@+id/btn_gz"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="广州" /></LinearLayout></RelativeLayout>二、天气预报数据分析1.数据描述2.数据类型-entity(WeatherInfo)编写一个实体类entity,描述天气信息的类型,包含6个字段:public class WeatherInfo {private String id;private String name;private String weather;private String temp;private String wind;private String pm;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public String getWeather() {return weather;}public void setWeather(String weather) { this.weather = weather;}public String getTemp() {return temp;}public void setTemp(String temp) {this.temp = temp;}public String getWind() {return wind;}public void setWind(String wind) {this.wind = wind;}public String getPm() {return pm;}public void setPm(String pm) {this.pm = pm;}}使用XML文件来描述天气信息。
Android获取新浪天气预报数据实例新浪天气预报地址:/xml.php?city=武汉&password=DJOYnieT8234jlsK&day=0其中,city后的城市可用.URLEncoder.encode(“武汉”,”gb2312”);也可以直接写”武汉”,但不能用”wuhan”。
Password固定Day为0表示当天天气,1表示第二天的天气,2表示第三天的天气,以此类推,最大为4。
工具类:1、定义成员1/** 新浪天气网址 */2public final String SINA_URL = "/xml.php";3/** 新浪天气XML调用密码 */4public final String PASSWORD = "DJOYnieT8234jlsK";5/** 城市 */6public String city;7/** 白天天气 */8public String status1;9/** 夜晚天气 */10public String status2;11/** 白天天气拼音 */12public String figure1;13/** 夜晚天气拼音 */14public String figure2;15/** 白天风向 */16public String direction1;17/** 夜晚风向 */18public String direction2;19/** 白天风级 */20public String power1;21/** 夜晚风级 */22public String power2;23/** 白天温度 */24public String temperature1;25/** 夜晚温度 */26public String temperature2;27/** 体感温度 */28public String tgd;29/** 紫外线指数 */30public String zwx_l;31/** 紫外线说明 */32public String zwx_s;33/** 体感度指数 */34public String ssd_l;35/** 体感度说明 */36public String ssd_s;37/** 空调指数 */38public String ktk_l;39/** 空调说明 */40public String ktk_s;41/** 洗车指数 */42public String xcz_l;43/** 洗车说明 */44public String xcz_s;45/** 穿衣指数 */46public String chy_l;47/** 穿衣说明 */48public String chy_shuoming;49/** 污染物扩散条件 */50public String pollution_l;51/** 污染物扩散条件说明 */52public String pollution_s;53/** 感冒指数 */54public String gm_l;55/** 感冒说明 */56public String gm_s;57/** 运动指数 */58public String yd_l;59/** 运动说明 */60public String yd_s;2、获取天气数据61/**62 * 更新天气63 *64 * @param city65 * 城市名66 * @param day67 * 0表示当天天气,1表示第二天的天气,2表示第三天的天气,以此类推,最大为468 */69public void UpdateWeatherInfo(String city, String day) {70if (city.equals("")) {71 isLoaded = false;72return;73 }74 String html = null;75try {76 html = doGet(SINA_URL + "?city="77 + .URLEncoder.encode(city, "gb2312") + "&password="78 + PASSWORD + "&day=" + day);7980 Document doc = Jsoup.parse(html);81if (doc.body().getElementsByTag("Profiles").size() == 0) { 82 isLoaded = false;83return;84 }85if(doc.body().getElementsByTag("Profiles").get(0).getElementsByTag("Weather ").size() == 0) {86 isLoaded = false;87return;88 }89 Element element = doc.body().getElementsByTag("Profiles").get(0)90 .getElementsByTag("Weather").get(0);9192this.city = element.getElementsByTag("city").text();93 status1 = element.getElementsByTag("status1").text();94 status2 = element.getElementsByTag("status2").text();95 figure1 = element.getElementsByTag("figure1").text();96 figure2 = element.getElementsByTag("figure2").text();97 direction1 = element.getElementsByTag("direction1").text();98 direction2 = element.getElementsByTag("direction2").text();99 power1 = element.getElementsByTag("power1").text();100 power2 = element.getElementsByTag("power2").text();101 temperature1 = element.getElementsByTag("temperature1").text();102 temperature2 = element.getElementsByTag("temperature2").text();103104 tgd = element.getElementsByTag("tgd").text();105 zwx_l = element.getElementsByTag("zwx_l").text();106 zwx_s = element.getElementsByTag("zwx_s").text();107 ssd_l = element.getElementsByTag("ssd_l").text();108 ssd_s = element.getElementsByTag("ssd_s").text();109 ktk_l = element.getElementsByTag("ktk_l").text();110 ktk_s = element.getElementsByTag("ktk_s").text();111 xcz_l = element.getElementsByTag("xcz_l").text();112 xcz_s = element.getElementsByTag("xcz_s").text();113 chy_l = element.getElementsByTag("chy_l").text();114 chy_shuoming = element.getElementsByTag("chy_shuoming").text();115 pollution_l = element.getElementsByTag("pollution_l").text();116 pollution_s = element.getElementsByTag("pollution_s").text();117 gm_l = element.getElementsByTag("gm_l").text();118 gm_s = element.getElementsByTag("gm_s").text();119 yd_l = element.getElementsByTag("yd_l").text();120 yd_s = element.getElementsByTag("yd_s").text();121122 isLoaded = true;123 } catch (UnsupportedEncodingException e) {124 isLoaded = false;125 }126 }3、访问网络127public static final String ENCODE = "utf-8";128129public static String doGet(String url) {130try {131 HttpGet httpGet = new HttpGet(url);132 HttpClient hc = new DefaultHttpClient();133 HttpResponse ht = hc.execute(httpGet);134if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 135 HttpEntity he = ht.getEntity();136 InputStream is = he.getContent();137 BufferedReader br = new BufferedReader(138new InputStreamReader(is));139 String response = "";140 String readLine = null;141while ((readLine = br.readLine()) != null) {142 response = response + readLine;143 }144 is.close();145 br.close();146return response;147 } else {148return"error";149 }150 } catch (Exception e) {151return"error";152 }153 }4、关于jsoup/view/4066913.htm。
Android开发_android如何通过Google Weather Api 获取天气预报信息获取天气的链接地址根据经纬度获取:/ig/api?weather=,,,31174165,121433841 【如中山的经纬度是:22.516997123628076,113.39263916015625 必须都乘以1000000才能作为参数】int a=(int)22.516997123628076*1000000;int b=(int)113.39263916015625*1000000;String strUrl ="/ig/api?hl=zh-cn&weather=,,,"+a+","+b; System.out.println(strUrl);根据地名获取:/ig/api?hl=zh-cn&weather=BeijingString strData ="";String strUrl = "/ig/api?hl=zh-cn&weather=ZhongShan";strData =getResponse(strUrl);//天气预报的xml存储在sd卡中new FileUnit().write(strData, "weather.xml");//SAX解析xmltry{SAXParserFactory spf = SAXParserFactory.newInstance();SAXParser sp =spf.newSAXParser();SAXReader saxReader =new SAXReader();InputSource is =new InputSource();is.setByteStream(newByteArrayInputStream(strData.getBytes()));sp.parse(is, saxReader);weatherList=saxReader.getWeathList();} catch(Exception e) {e.printStackTrace();}//显示天气预报showWeather();根据地址获得xml的Stringprotected String getResponse(String queryURL) {URL url;try{url =new URL(queryURL.replace("", "%20"));URLConnection urlconn =url.openConnection();urlconn.connect();InputStream is =urlconn.getInputStream();BufferedInputStream bis =new BufferedInputStream(is);ByteArrayBuffer buf =new ByteArrayBuffer(50);int read_data =-1;while((read_data =bis.read()) !=-1) {buf.append(read_data);}//String resp = buf.toString();String resp =EncodingUtils.getString(buf.toByteArray(), "GBK");return resp;} catch(MalformedURLException e) {//TODO Auto-generated catch blocke.printStackTrace();return"";} catch(IOException e) {//TODO Auto-generated catch blocke.printStackTrace();return"";}显示天气private void showWeather(){List<String>weather=null;String strTemp="";for(int i=0; i<weatherList.size();i++){weather=weatherList.get(i);strTemp+="\n==========================\n";for(int j=0;j<weather.size();j++){strTemp+=weather.get(j)+"\n";}}tvShow.setText(strTemp);}SAXReader:package com.ReadOrder;import java.util.ArrayList;import java.util.List;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class SAXReader extends DefaultHandler {private final String FORECASE_INFORMATION="forecast_information";private final String CURRENT_CONDITIONS="current_conditions";private final String FORECAST_CONDITIONS="forecast_conditions";private List<List<String>>weatherList =null;private List<String>weather =null;private static String tagname ="";@Overridepublic void startDocument() throws SAXException {weatherList =new ArrayList<List<String>>();}@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {if(localName.equals(FORECASE_INFORMATION)||localName.equals(CURRENT_CONDITIONS)||localName.equals(FORECAST_CONDITIONS)) {tagname ="current_conditions";weather =new ArrayList<String>();}else{if(tagname.equals(CURRENT_CONDITIONS)&& attributes.getValue("data") !=null) {weather.add (attributes.getValue("data"));System.out.println("###"+attributes.getValue("data"));}}}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {if(localName.equals(FORECASE_INFORMATION)||localName.equals(CURRENT_CONDITIONS)||localName.equals(FORECAST_CONDITIONS)) {weatherList.add(weather);weather=null;tagname="";}}@Overridepublic void endDocument() throws SAXException {}public List<List<String>>getWeathList() { if(weatherList==null||weatherList.size()<1){return null;}else{for(int i=0;i<weatherList.size();i++){System.out.println(weatherList.get(i)); }return weatherList;}}}详细代码:package com.ReadOrder;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import .HttpURLConnection;import .MalformedURLException;import .URL;import .URLConnection;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import javax.crypto.spec.IvParameterSpec;import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.apache.http.util.ByteArrayBuffer;import org.apache.http.util.EncodingUtils;import org.w3c.dom.ls.LSException;import org.xml.sax.InputSource;import org.xml.sax.SAXException;import android.R.integer;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.TextView;public class GoogleWeatherActivity extends Activity {TextView tvShow;List<List<String>>weatherList=null;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setTitle("获取天气预报");setContentView(yout_weather);tvShow =(TextView) findViewById(R.id.TextView001); tvShow.setText("None Data");findViewById(R.id.btnGetWeather).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {System.out.println("btnGetWeather===>onclick");String strData ="";String strUrl ="/ig/api?hl=zh-cn&weather=ZhongShan";strData =getResponse(strUrl);//天气预报的xml存储在sd卡中new FileUnit().write(strData, "weather.xml");//SAX解析xmltry{SAXParserFactory spf = SAXParserFactory.newInstance();SAXParser sp =spf.newSAXParser();SAXReader saxReader =new SAXReader();InputSource is =new InputSource();is.setByteStream(newByteArrayInputStream(strData.getBytes()));sp.parse(is, saxReader);weatherList=saxReader.getWeathList();} catch(Exception e) {e.printStackTrace();}//显示天气预报showWeather();}});}private void showWeather(){List<String>weather=null;String strTemp="";for(int i=0; i<weatherList.size();i++){weather=weatherList.get(i);strTemp+="\n==========================\n";for(int j=0;j<weather.size();j++){strTemp+=weather.get(j)+"\n";}}tvShow.setText(strTemp);}protected String getResponse(String queryURL) {URL url;try{url =new URL(queryURL.replace("", "%20"));URLConnection urlconn =url.openConnection();urlconn.connect();InputStream is =urlconn.getInputStream();BufferedInputStream bis =new BufferedInputStream(is);ByteArrayBuffer buf =new ByteArrayBuffer(50);int read_data =-1;while((read_data =bis.read()) !=-1) {buf.append(read_data);}//String resp = buf.toString();String resp =EncodingUtils.getString(buf.toByteArray(), "GBK");return resp;} catch(MalformedURLException e) {//TODO Auto-generated catch block e.printStackTrace();return"";} catch(IOException e) {//TODO Auto-generated catch block e.printStackTrace();return"";}}}。
查询城市天气预报信息主页面WeatherActivity继承android.app.Activity, 并重写onCreate 方法。
onCreate 方法是查询页面的初始化方法,在这个方法中我们要初始化页面中Button,Spinner 等控件信息。
showCity 方法,列表显示查询天气预报信息的城市名称。
updateWeatherInfoView 方法,更新显示选中城市的当前天气信息。
updateWeatherorecastView 方法,更新显示选中城市未来四天的天气信息。
getCityWeather 方法,通过网络得到选中城市的天气预报信息。
查询城市天气预报详细信息页面WeatherDetailActivity 继承android.app.Activity, 并重写onCreate 方法。
onCreate 方法是查询天气预报详细页面的初始化方法,在这个方法中我们要初始化页面中TextView 等控件信息。
showDetailInfo 方法,得到查询目标城市的天气预报的风向、能见度、相对湿度等详细信息。
1.5 系统实现代码解析1.5.1 Android 客户端系统配置文件AndroidManifest.xml 是系统中的配置文件,我们需要将系统中用到的Android 组件都在这个文件中注册,其中WeatherActivity 是显示天气预报的主页面,WeatherDetailActivity 是显示天气预报详细的的页面。
为了访问Google 提供天气预报信息的站点和能够访问提供选定城市更多信息的Web Service 必须为系统开放访问Internet 的权限:<uses-permissionandroid:name="android.permission.INTERNET"></uses-permission>。
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="/apk/res/android"package="com.miiceic.weather.activity"android:versionCode="1"android:versionName="1.0"><application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".WeatherActivity"android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="UNCHER" /></intent-filter></activity><activity android:name=".WeatherDetailActivity"></activity></application><uses-sdk android:minSdkVersion="3" /><uses-permissionandroid:name="android.permission.INTERNET"></uses-permission></manifest>代码清单1 AndroidManifest.xml第12 页共31 页1.5.2 Android 城市天气预报系统布局文件城市天气预报主页面布局采用XML 形式,文件放置在\res\layout\main.xml 中。
android --天气预报今天参考了别人的关于android平台的天气预报,自己也修改后实现自己要实现的格式,特地拿出来分享:首先要导入第三方包:ksoap2-android-assembly-2.4-jar-with-dependencies.jar主程序的代码:package com.sebservice;import java.io.IOException;import java.io.UnsupportedEncodingException;import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObject;import org.ksoap2.serialization.SoapSerializationEnvelope;import org.ksoap2.transport.HttpTransportSE;import org.xmlpull.v1.XmlPullParserException;import android.app.Activity;import android.app.AlertDialog;import android.app.AlertDialog.Builder;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class WebsActivity extends Activity {private Button okButton;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main);okButton = (Button) this.findViewById(R.id.bt1);okButton.setOnClickListener(new Button.OnClickListener() {@Overridepublic void onClick(View v) {String city = "北京";getWeather(city);}});}private static final String NAMESPACE = "/";// WebService地址private static String URL = "/webservices/weatherw ebservice.asmx";private static final String METHOD_NAME = "getWeatherbyCityName";private static String SOAP_ACTION = "/getWeatherbyCity Name";private String weatherToday;private SoapObject detail;public void getWeather(String cityName) {try {SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);rpc.addProperty("theCityName", cityName);SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnve lope.VER11);envelope.bodyOut = rpc;envelope.dotNet = true;envelope.setOutputSoapObject(rpc);HttpTransportSE ht = new HttpTransportSE(URL);ht.debug = true;ht.call(SOAP_ACTION, envelope);detail =(SoapObject) envelope.getResponse();getw(detail,city);return;} catch (Exception e) {e.printStackTrace();}}private void getw(SoapObject detail,String local)throws UnsupportedEncodingEx ception{String str=detail.getProperty(6).toString();String show="所查城市:"+local;show=show+"\n今天是:"+str.split(" ")[0];show=show+"\n天气:"+str.split(" ")[1];show=show+"\n风级:"+detail.getProperty(7).toString().split(" ")[0];show=show+"\n"+detail.getProperty(10).toString().split(" ")[0];show=show+"\n温馨提示:\n"+detail.getProperty(11).toString().split(" ")[0]; Builder al=new AlertDialog.Builder(this);al.setTitle("天气预报");al.setPositiveButton("确定", null);al.setMessage(show.toString());al.create().show();}}布局文件的内容是:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android" android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/hello" /><Buttonandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:id="@+id/bt1"android:text="查看北京天气"/></LinearLayout>3、还要在androidmanifest.xml加入权限<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="/apk/res/android" package="com.sebservice"android:versionCode="1"android:versionName="1.0" ><uses-sdk android:minSdkVersion="10" /><applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name" ><activityandroid:label="@string/app_name"android:name=".WebsActivity" ><intent-filter ><action android:name="android.intent.action.MAIN" /><category android:name="UNCHER" /></intent-filter></activity></application><uses-permission android:name="android.permission.INTERNET"></uses-permi ssion></manifest>分类: android。
用Android Studio新建一个默认工程后,将第一张图片红色标记文件修改到相应代码即可<uses-permission android:name="android.permission.INTERNET"/>package com.example.rui.weatherforecast;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.EditText;import android.widget.Toast;import com.google.gson.Gson;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import .HttpURLConnection;import .MalformedURLException;import .ProtocolException;import .URL;public class MainActivity extends AppCompatActivity {EditText et_city, et_weather, et_highTemp, et_lowTemp;Weatherinfo weatherinfo;Weatherinfo.Weather weather;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);init();}/*** 初始化控件并开始事件*/public void init() {//获取控件et_city = (EditText) findViewById(R.id.city);et_weather = (EditText) findViewById(R.id.weather);et_highTemp = (EditText) findViewById(R.id.highTemp);et_lowTemp = (EditText) findViewById(R.id.lowTemp);/*** 新建线程进行查询天气*/new Thread() {@Overridepublic void run() {String strurl = "/data/cityinfo/101010100.html"; try {getweathers(strurl);} catch (MalformedURLException e) {e.printStackTrace();}}}.start();}/*** 子线程响应处理*/Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);if (msg.what == 1) {Toast.makeText(MainActivity.this, "天气" +weatherinfo.getWeatherinfo().getCity() + weatherinfo.getWeatherinfo().getTemp1(), Toast.LENGTH_SHORT).show();et_city.setText(weather.getCity());et_weather.setText(weather.getWeather());et_lowTemp.setText(weather.getTemp1());et_highTemp.setText(weather.getTemp2());}}};/*** 解析JSON数据转换并赋值到实体类中** @param path* @throws MalformedURLException*/public void getweathers(String path) throws MalformedURLException {String strjson = (String) getConnetion(path);Gson gson = new Gson();weatherinfo = gson.fromJson(strjson, Weatherinfo.class);weather = weatherinfo.getWeatherinfo();//完成后发送消息给Handler进行下一个事件Message msg = new Message();msg.what = 1;mHandler.sendMessage(msg);}/*** 联网获取JSON数据** @param path* @return* @throws MalformedURLException*/public String getConnetion(String path) throws MalformedURLException {URL url = new URL(path);try {HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000);connection.setReadTimeout(5000);connection.setRequestMethod("GET");InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String line = bufferedReader.readLine().toString();bufferedReader.close(); inputStreamReader.close();return line;} catch (ProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}}package com.example.rui.weatherforecast;/*** Created by Rui on 2018/1/2.*/public class Weatherinfo {private Weather weatherinfo;public Weather getWeatherinfo() {return weatherinfo;}public void setWeatherinfo(Weather weatherinfo) { this.weatherinfo = weatherinfo;}public class Weather{private String city;private String cityid;private String temp1;private String temp2;private String weather;private String img1;private String img2;private String ptime;public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getCityid() {return cityid;}public void setCityid(String cityid) {this.cityid = cityid;}public String getTemp1() {return temp1;}public void setTemp1(String temp1) {this.temp1 = temp1;public String getTemp2() {return temp2;}public void setTemp2(String temp2) { this.temp2 = temp2;}public String getWeather() {return weather;}public void setWeather(String weather) { this.weather = weather;}public String getImg1() {return img1;}public void setImg1(String img1) {this.img1 = img1;}public String getImg2() {return img2;}public void setImg2(String img2) {this.img2 = img2;}public String getPtime() {return ptime;}public void setPtime(String ptime) { this.ptime = ptime;}}}<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android" android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="城市:" />-<EditTextandroid:id="@+id/city"android:layout_width="match_parent"android:layout_height="wrap_content"android:ems="10"><requestFocus /></EditText><TextViewandroid:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="天气:" /><EditTextandroid:id="@+id/weather"android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" /><TextViewandroid:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="最高温度:" /><EditTextandroid:id="@+id/highTemp"android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" /><TextViewandroid:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="最低温度:" /><EditTextandroid:id="@+id/lowTemp"android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" /></LinearLayout>compile 'com.google.code.gson:gson:2.8.2'。
如何通过AndroidStduio来编写⼀个完整的天⽓预报APP⽬录⼀、项⽬概述⼆、功能分析三、开发环境四、涉及知识点五、项⽬演⽰六、项⽬总结七、项⽬源码⼀、项⽬概述本次项⽬主要实现了天⽓预报功能。
通过调⽤天⽓预报接⼝来获得天⽓数据,⽤LIstView和GridView来搭建每个界⾯,将查询的天⽓信息存储在SQLiteDatabase中。
应⽤包括了五⼤界⾯:⾸页⾯:有各种组件装饰,显⽰天⽓、温度、风向及各种指数,还有未来三天的天⽓城市管理界⾯:在这⾥可以对添加的城市进⾏管理搜索更多城市页⾯:可以添加想要查看的城市删除城市页⾯:可以删除已经添加的城市信息更多设置页⾯:可以设置壁纸、查看版本信息和分享软件⼆、功能分析通过天⽓预报接⼝获取⽹络数据展⽰选择城市的天⽓情况、温度、风向,各种指数以及未来三天的基础天⽓情况将从⽹络中获取到的城市信息保存到数据库中,便于没有⽹时候进⾏数据请求对数据库中的存储的信息,进⾏增删改查等操作三、开发环境四、涉及知识点五、项⽬演⽰1、打开项⽬,运⾏APP,显⽰⾸页⾯天⽓及各项指数等信息。
2、点击左下⾓的+号,进⼊城市管理页⾯。
3、再点击右下⾓的添加按钮,进⼊城市添加界⾯,在这⾥选择你想要查看的城市4、我们选择【上海】,⾃动跳转到主页⾯,显⽰上海的天⽓的信息5、这时候我们再依次添加【深圳】【沈阳】两座城市,可以看到城市和天⽓信息⽴刻就更新了6、这时候我们可以滑动这个界⾯,下⾯的指⽰点对应的已经添加的城市,现在看到⼀共有4个城市,也就是有4页,我们向左滑动到第⼀页【苏州】7、这些穿⾐指数、洗车指数等指数点击都会有温馨的提⽰框,⾮常⼈性化8、我们继续进⼊到城市管理界⾯,这⾥可以对城市进⾏删除,然后点击右上⾓的保存按钮9、我们点击主页⾯的右下⾓的三个点按钮,显⽰更多设置10、我们选择改变壁纸,⼀共有三款可以选择,选择完毕⽴即进⾏主题更改11、觉得软件很不错的话,还可以分享本软件给好友六、项⽬总结本次项⽬通过调⽤天⽓接⼝实现天⽓预报的功能,逻辑实现上还是⽐较复杂的,属于进阶项⽬,通过对这次项⽬的学习,可以加深基础控件和Activity的理解,还会知道如何使⽤第三⽅框架。
在Android Studio中开发一个简单的天气应用随着智能手机的普及,天气应用成为了人们生活中不可或缺的一部分。
通过天气应用,我们可以随时随地了解到当前的天气情况以及未来几天的天气预报,这对于出门旅游、安排活动等都非常有帮助。
本文将介绍如何在Android Studio中开发一个简单的天气应用。
首先,我们需要一个天气数据源。
目前,许多天气数据提供商都提供了API接口供开发者使用,例如心知天气和和风天气。
我们可以选择其中一个数据源,通过接口获取天气数据。
接下来,在Android Studio中创建一个新的项目。
我们可以选择使用Java或者Kotlin进行开发,这里我选择使用Java。
创建好项目后,需要配置所选天气数据源的API接口。
为了获取天气数据,我们需要使用网络请求库。
在Android开发中,最常用的网络请求库是OkHttp和Retrofit。
在项目的build.gradle文件中引入所选网络请求库的依赖,然后进行网络请求的配置。
根据所选API接口的要求,设置请求的URL、参数和请求方式。
当请求返回天气数据时,我们需要对数据进行解析。
可以使用JSON解析库来处理返回的JSON数据,例如Gson。
通过解析,我们可以提取出所需的天气信息,包括当前的天气情况、温度、湿度、风力等。
接下来,我们需要设计一个用户界面来展示天气信息。
可以使用Android自带的UI组件来构建界面,例如TextView、ImageView和RecyclerView。
例如,我们可以使用TextView来显示当前的天气情况,ImageView来显示天气图标,RecyclerView来展示未来几天的天气预报。
为了提高用户体验,我们可以在界面中添加一些额外功能。
例如,可以使用定位功能获取用户的当前位置,然后自动显示该地区的天气信息。
还可以添加刷新功能,允许用户手动更新天气数据。
在设计界面时,还可以考虑一些简单的动画效果和过渡效果,来使界面更加生动和流畅。
Android 3.0自带的天气预报例子代码Android 3.0正式版API Level 11中加入了一个天气预报例子,下面是manifest.xml中的关键代码,只是少了xml的编码头:XML/HTML代码1.<manifestxmlns:android="/apk/res/android"2.package="com.example.android.weatherlistwidget">3.<uses-sdkandroid:minSdkVersion="11"/>4.<applicationandroid:label="WeatherWidgetSample">5.<receiverandroid:name="WeatherWidgetProvider">6.<intent-filter>7.<actionandroid:name="android.appwidget.action.APPWIDGET_UPDATE"/>8.</intent-filter>9.<meta-dataandroid:name="android.appwidget.provider"10.android:resource="@xml/widgetinfo"/>11.</receiver>12.<serviceandroid:name="WeatherWidgetService"13.android:permission="android.permission.BIND_REMOTEVIEWS"14.android:exported="false"/>15.<providerandroid:name="WeatherDataProvider"16.android:authorities="com.example.android.weatherlistwidget.provider"/>17.</application>18.</manifest>这里WeatherDataProvider.Java的源码为主要是ContentProvider相关的处理,这里作为appWidget的receiver Java代码1.classWeatherDataPoint{2.Stringcity;//城市3.intdegrees;//度数4.WeatherDataPoint(Stringc,intd){5.city=c;6.degrees=d;7.}8.}9.publicclassWeatherDataProviderextendsContentProvider{10.publicstaticfinalUriCONTENT_URI=11.Uri.parse("content://com.example.android.weatherlistwidget.provider");12.publicstaticclassColumns{13.publicstaticfinalStringID="_id";14.publicstaticfinalStringCITY="city";15.publicstaticfinalStringTEMPERATURE="temperature";16.}17.privatestaticfinalArrayList<WeatherDataPoint>sData=newArrayList<WeatherDataPoint>();18.@Override19.publicbooleanonCreate(){20.sData.add(newWeatherDataPoint("SanFrancisco",13));21.sData.add(newWeatherDataPoint("NewYork",1));22.sData.add(newWeatherDataPoint("Seattle",7));23.sData.add(newWeatherDataPoint("Boston",4));24.sData.add(newWeatherDataPoint("Miami",22));25.sData.add(newWeatherDataPoint("Toronto",-10));26.sData.add(newWeatherDataPoint("Calgary",-13));27.sData.add(newWeatherDataPoint("Tokyo",8));28.sData.add(newWeatherDataPoint("Kyoto",11));29.sData.add(newWeatherDataPoint("London",-1));30.sData.add(newWeatherDataPoint("Nomanisan",27));31.returntrue;32.}33.@Override34.publicsynchronizedCursorquery(Uriuri,String[]projection,Stringselection,35.String[]selectionArgs,StringsortOrder){36.assert(uri.getPathSegments().isEmpty());37.finalMatrixCursorc=newMatrixCursor(38.newString[]{Columns.ID,Columns.CITY,Columns.TEMPERATURE});39.for(inti=0;i<sData.size();++i){40.finalWeatherDataPointdata=sData.get(i);41.c.addRow(newObject[]{newInteger(i),data.city,newInteger(data.degrees)});42.}43.returnc;44.}45.@Override46.publicStringgetType(Uriuri){47.return"vnd.android.cursor.dir/vnd.weatherlistwidget.citytemperature";48.}49.@Override50.publicUriinsert(Uriuri,ContentValuesvalues){51.returnnull;52.}53.@Override54.publicintdelete(Uriuri,Stringselection,String[]selectionArgs){55.return0;56.}57.@Override58.publicsynchronizedintupdate(Uriuri,ContentValuesvalues,Stringselection,59.String[]selectionArgs){60.assert(uri.getPathSegments().size()==1);61.finalintindex=Integer.parseInt(uri.getPathSegments().get(0));62.finalMatrixCursorc=newMatrixCursor(63.newString[]{Columns.ID,Columns.CITY,Columns.TEMPERATURE});64.assert(0<=index&&index<sData.size());65.finalWeatherDataPointdata=sData.get(index);66.data.degrees=values.getAsInteger(Columns.TEMPERATURE);67.getContext().getContentResolver().notifyChange(uri,null);68.return1;69.}70.}上面可以看到,对于插入和删除没有做过多的处理,对于天气更新给出了详细的解决方法。
通过google接口在Android中实现天气预报效果Android可以通过google实现获取指定经纬度位置或者某一个城市的天气信息。
如果是根据经纬度查询天气信息,需要对精度为进行转换,例如lat值为31.174165,需要过滤掉小数点,变为31174165传到接口中,维度也一样处理,处理后传给/ig/api?weather=,,,31174165,121433841既可以获取数据。
这里要注意一个问题,如果大家获取的经纬度序列很长,直接去掉小数点,有时候也无法获取天气信息,例如40.478224838152528,124.97828006744385,去掉小数点后,传到参数位置,无法获取值,需要大家将经纬度按下面方式转换一下,只取小数点后6位就可以了。
int latI = (int) (lat * 1E6);int lonI = (int) (lon * 1E6);下面的例子演示了根据输入城市,获取该城市的天气预报,Weather.java的61行,是根据经纬度获取天气信息。
工程结构:Weather.java类package com.AndroidWeather;import java.io.InputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils;import org.w3c.dom.Document;import org.w3c.dom.NodeList;import org.xml.sax.InputSource;import android.app.Activity;import android.graphics.Bitmap;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;public class Weather extends Activity {public EditText ETplace;public TextView TvPlace;public Button query;public TextView placeName;public ImageView imView;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main1);ETplace = (EditText) findViewById(R.id.place);query = (Button) findViewById(R.id.query);imView = (ImageView) findViewById(R.id.myImageView);placeName = (TextView) findViewById(Place);query.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {try {TvPlace = (TextView)findViewById(Place);// String place =ETplace.getText().toString();String place =CntoSpell.getFullSpell(ETplace.getText().toString());placeName.setText(place);String weather = "";// String url ="/ig/api?&weather="// + place;String url ="/ig/api?weather=,,,31174165,121433841";DefaultHttpClient client = new DefaultHttpClient();HttpUriRequest req = new HttpGet(url);HttpResponse resp = client.execute(req);// String strResult =//EntityUtils.toString(resp.getEntity());// Log.i("weather->", strResult);// 一华氏度等于9/5摄氏度数值+32HttpEntity ent = resp.getEntity();InputStream stream = ent.getContent();DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();Document d = b.parse(newInputSource(stream));NodeList n =d.getElementsByTagName("forecast_conditions");// 获得图片url 当天的。
String imgUrl = "";imgUrl +=n.item(0).getChildNodes().item(3).getAttributes().item(0).getNodeValue();imView.setImageBitmap(Utils.returnBitMap(imgUrl));// 今后4天预报for (int i = 0; i < n.getLength(); i++) {weather +=Utils.week(n.item(i).getChildNodes().item(0).getAttributes().item(0).getNodeValue());weather += ", ";weather += (Integer.parseInt(n.item(i).getChildNodes().item(1).getAttributes().item(0).getNodeValue()) - 32) * 5 / 9;weather += " ~ ";weather += (Integer.parseInt(n.item(i).getChildNodes().item(2).getAttributes().item(0).getNodeValue()) - 32) * 5 / 9;weather += ", ";weather += Utils.weather(n.item(i).getChildNodes().item(4).getAttributes().item(0).getNodeValue());weather += "\n";}Log.i("parseed weather->", weather);TvPlace.setText(weather);} catch (Exception e) {e.printStackTrace();}}});}}Utils类:package com.AndroidWeather;import java.io.IOException;import java.io.InputStream;import .HttpURLConnection;import .MalformedURLException;import .URL;import android.graphics.Bitmap;import android.graphics.BitmapFactory;public class Utils {public static String week(String enWeek) {if (enWeek.equals("Mon") || enWeek.equals("Monday"))return"星期一";else if (enWeek.equals("Tue") || enWeek.equals("Tuesday"))return"星期二";else if (enWeek.equals("Wed") ||enWeek.equals("Wednesday"))return"星期三";else if (enWeek.equals("Thu") ||enWeek.equals("Thursday"))return"星期四";else if (enWeek.equals("Fri") || enWeek.equals("Friday"))return"星期五";else if (enWeek.equals("Sat") ||enWeek.equals("Saturday"))return"星期六";else if (enWeek.equals("Sun") || enWeek.equals("Sunday"))return"星期日";return"";}public static String weather(String enWeather) {if (enWeather.equals("Clear"))return"晴";else if (enWeather.equals("Partly Sunny")|| enWeather.equals("partly_cloudy"))return"多云";else if (enWeather.equals("Chance of Rain"))return"晴转雨";else if (enWeather.equals("storm"))return"暴雨";else if (enWeather.equals("thunderstorm"))return"雷阵雨";else if (enWeather.equals("fog"))return"大雾";else if (enWeather.equals("haze"))return"有雾";else if (enWeather.equals("rain"))return"雨";else if (enWeather.equals("heavyrain"))return"大雨";else if (enWeather.equals("lightrain"))return"小雨";else if (enWeather.equals("heavyrain"))return"大雨";else if (enWeather.equals("snow"))return"有雪";// / 还需要补充。