智能手机应用程序开发是软件开发的一个新的热点,但如何才能跨入这道门楣呢?今天我通过为自己的多普达565手机添加一个天气预报程序来向大家讲解一下。我们都知道QQ有一个免费提供给Blog引用的天气预报服务网址http://appnews.qq.com/cgi-bin/news_qq_search?city=上海(上海是我自己所在城市,如果想看自己的城市,在浏览器中改成城市名称即可),现在我使用QQ提供的这个服务,将其包装部署为一个Web服务,并编写程序使得我的多普达565智能手机能使用这个Web服务。
设备要求:
PC开发环境:Windows XP SP2,Visual Studio 2003.NET,.NET Framework 1.1 SP1
操作系统:Windows Mobile(TM) 2003第二版,版本4.21.1088(Build 14235.2.0.0)
智能手机:多普达565
一、环境安装
首先我们必须安装.NET Mobile所需要的开发环境,必须安装的软件(如下软件都是微软提供免费下载和使用的)
1、Microsoft ActiveSync 3.7.1
下载网址:http://www.microsoft.com/windowsmobile/downloads/activesync37.mspx,里面有中文版本,或者,在手机附带的微软光盘里面有安装程序;最新版本Microsoft ActiveSync 3.8出来了,可以到摘要的页面中去找链接下载,但这个程序我还是用的老版本。
作用:同步手机和PC机数据的程序
2、Microsoft SMARTPHONE 2003 SDK.msi
下载网址:
http://download.microsoft.com/download/e/3/1/e310bb99-2f33-4d79-bb8a-41d9cb3c79b4/Microsoft SMARTPHONE 2003 SDK.msi
3、MobileAppDevToolkit2004.exe
下载地址:http://download.microsoft.com/download/b/2/5/b25742c0-daa3-4a8c-988d-a947a35e0a68/MobileAppDevToolkit2004.exe
二、设计并部署WebService
1、建立一个名为WeatherService的WebService,并将QQ的天气服务转为XML WebService服务,部署在一台具有固定IP的服务器上。
2、新建一个WeatherDataSet.XSD,存储我们的天气信息
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="WeatherDataSet" targetNamespace="Ezhi.Services.WeatherService" elementFormDefault="qualified"
attributeFormDefault="qualified" xmlns="Ezhi.Services.WeatherService" xmlns:mstns="Ezhi.Services.WeatherService"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="WeatherDataSet" msdata:IsDataSet="true">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element name="WeatherDS">
<xs:complexType>
<xs:sequence>
<xs:element name="CityName" type="xs:string" minOccurs="0" />
<xs:element name="Date1" type="xs:string" minOccurs="0" />
<xs:element name="Weather1" type="xs:string" minOccurs="0" />
<xs:element name="Temp1" type="xs:string" minOccurs="0" />
<xs:element name="WindPower1" type="xs:string" minOccurs="0" />
<xs:element name="Date2" type="xs:string" minOccurs="0" />
<xs:element name="Weather2" type="xs:string" minOccurs="0" />
<xs:element name="Temp2" type="xs:string" minOccurs="0" />
<xs:element name="WindPower2" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
3、WeatherService的源代码如下
#region Using directives
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Net;
using System.Text;
#endregion
namespace WeatherService
{
/// <summary>
/// Service1 的摘要说明。
/// </summary>
[WebService(Description="WeatherService 天气Service",Namespace="WeatherService")]
public class Weather : System.Web.Services.WebService
{
#region Variable
private string tommorow;
#endregion
#region 构造函数
public Weather()
{
InitializeComponent();
if(DateTime.Today.AddDays(1).Month.ToString().Length == 1)
{
tommorow= "0"+DateTime.Today.AddDays(1).Month.ToString()+"月" +
DateTime.Today.AddDays(1).Day.ToString()+"日";
}
else
{
tommorow= DateTime.Today.AddDays(1).Month.ToString()+"月" +
DateTime.Today.AddDays(1).Day.ToString()+"日";
}
}
#endregion
#region 组件设计器生成的代码
//Web 服务设计器所必需的
private IContainer components = null;
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region [OK] GetWeatherDataSet 天气预报
[WebMethod(Description="天气预报")]
public DataSet GetWeatherDataSet(string cityName)
{
string url=@"http://appnews.qq.com/cgi-bin/news_qq_search";
string weatherData="";
try
{
weatherData = GetPage(url,cityName).Replace(" ","").Trim();
}
catch(Exception)
{
throw new Exception("对不起,没有这个城市的天气信息!");
}
//System.Diagnostics.Trace.WriteLine( tommorow );
//System.Diagnostics.Trace.WriteLine( weatherData );
WeatherDataSet weatherDs = new WeatherDataSet();
weatherDs.WeatherDS.AddWeatherDSRow(GetWeatherRow(ref weatherDs,weatherData,cityName) );
return weatherDs;
}
private WeatherDataSet.WeatherDSRow GetWeatherRow(ref WeatherDataSet weatherDs,string weatherData,string cityName)
{
WeatherDataSet.WeatherDSRow weatherRow = weatherDs.WeatherDS.NewWeatherDSRow();
weatherRow.CityName = weatherData.Substring(weatherData.IndexOf("●")+1,cityName.Length);
weatherRow.Date1 = DateTime.Now.ToLongDateString();
weatherRow.Weather1 = weatherData.Substring(weatherData.IndexOf("天气")+"天气".Length,weatherData.IndexOf("气温")-(weatherData.IndexOf("天气")+"天气".Length));
weatherRow.Temp1 = weatherData.Substring(weatherData.IndexOf("气温")+"气温".Length,weatherData.IndexOf("风力")-(weatherData.IndexOf("气温")+"气温".Length)).Replace("℃-","℃/");
weatherRow.WindPower1 = weatherData.Substring(weatherData.IndexOf("风力")+"风力".Length,weatherData.IndexOf(tommorow)-(weatherData.IndexOf("风力")+"风力".Length));
weatherRow.Date2 = DateTime.Today.AddDays(1).ToLongDateString();
weatherRow.Weather2 = weatherData.Substring(weatherData.LastIndexOf("天气")+"天气".Length,weatherData.LastIndexOf("气温")-(weatherData.LastIndexOf("天气")+"天气".Length));
weatherRow.Temp2 = weatherData.Substring(weatherData.LastIndexOf("气温")+"气温".Length,weatherData.LastIndexOf("风力")-(weatherData.LastIndexOf("气温")+"气温".Length)).Replace("℃-","℃/");
weatherRow.WindPower2 = weatherData.Substring(weatherData.LastIndexOf("风力")+"风力".Length);
return weatherRow;
}
#endregion
#region GetPageString 获取QQ的天气服务
//private string xx="";
[WebMethod(Description="天气预报")]
public string GetPageString(string cityName)
{
string url=@"http://appnews.qq.com/cgi-bin/news_qq_search";
return GetPage(url,cityName);
}
private static string GetPage(string url,string cityName)
{
HttpWebResponse res = null;
string strResult = "";
try
{
string postData = "city=" + HttpUtility.UrlEncode(cityName,System.Text.Encoding.GetEncoding("GB2312"));
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.KeepAlive = true;
req.ContentType = "application/x-www-form-urlencoded";
StringBuilder UrlEncoded = new StringBuilder();
byte[] SomeBytes = Encoding.ASCII.GetBytes(postData);
req.ContentLength = SomeBytes.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
//获得流内容
res = (HttpWebResponse)req.GetResponse();
System.IO.Stream s=res.GetResponseStream();
StreamReader reader = new StreamReader(s,System.Text.Encoding.Default);
strResult=reader.ReadToEnd();
}
catch(Exception e)
{
strResult = e.ToString();
}
finally
{
if ( res != null )
{
res.Close();
}
}
strResult=strResult.Remove(0,strResult.IndexOf("●"));
if( cityName != "北京" )
{
strResult=strResult.Remove(strResult.IndexOf("北京"),strResult.Length-strResult.IndexOf("北京"));
}
else
{
strResult=strResult.Remove(strResult.LastIndexOf("北京"),strResult.Length-strResult.LastIndexOf("北京"));
}
strResult=strResult.Trim();
while(strResult.IndexOf(@"<") != -1)
{
strResult=strResult.Remove(strResult.IndexOf(@"<"),strResult.IndexOf(@">")-strResult.IndexOf(@"<")+1);
}
while(strResult.IndexOf(@" ") != -1)
{
strResult=strResult.Replace(" ","");
}
string x = Encoding.UTF8.GetString(new Byte[]{10});
string y = Encoding.UTF8.GetString(new Byte[]{9});
while(strResult.IndexOf(x) != -1)
{
strResult=strResult.Replace(x,"");
}
while(strResult.IndexOf(y) != -1)
{
strResult=strResult.Replace(y,"");
}
return strResult;
}
#endregion
}
}
记得将在Web.Config文件加入以下节点,使得WebService能被外部访问
<!-- WebService 获取的途径 -->
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="HttpPostLocalhost"/?
<add name="Documentation"/>
</protocols>
</webServices>
三、新建手机应用程序项目
1、新建一个智能设备应用程序,在主面板上拖放如图2所示的几个控件,其中timer是用来检查是否数据已经下载完毕的。
图1-新建智能设备应用程序 |
图2-界面设计 |
2、引用建好的WebService
图3-引用WebService |
3、WeatherService智能手机上运行的程序源代码
using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Data;
namespace WeatherService { /// <summary> /// Summary description for MainForm. /// </summary>
public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.ComboBox comboBox_City; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.Label txt_Weather1; private System.Windows.Forms.Label txt_Date1; private System.Windows.Forms.Label txt_Temp1; private System.Windows.Forms.Label txt_WindPower1; private System.Windows.Forms.Label txt_Temp2; private System.Windows.Forms.Label txt_WindPower2; private System.Windows.Forms.Label txt_Date2; private System.Windows.Forms.Label txt_Weather2; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem_Menu; private System.Windows.Forms.MenuItem menuItem_Exit; private System.Windows.Forms.Label label_City; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.MenuItem menuItem2; private System.Windows.Forms.MenuItem menuItem3;
public string[] cityList = new string[] { "北京", "上海", "天津", "石家庄", "哈尔滨", "沈阳", "长春", "太原", "济南", "郑州", "天津", "呼和浩特", "西安", "银川", "兰州", "西宁", "乌鲁木齐", "合肥", "南昌", "南京", "杭州", "武汉", "长沙", "广州", "深圳", "福州", "厦门", "南宁", "桂林", "海口", "重庆", "成都", "贵阳", "昆明", "拉萨", "香港", "澳门", "台北", };
public MainForm() { InitializeComponent(); foreach( string x in cityList) { this.comboBox_City.Items.Add(x); }
this.comboBox_City.SelectedIndex = 0; }
/// <summary> /// Clean up any resources being used. /// </summary>
protected override void Dispose( bool disposing ) { base.Dispose( disposing ); }
#region Windows Form Designer generated code
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary>
private void InitializeComponent() { this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem_Menu = new System.Windows.Forms.MenuItem(); this.menuItem_Exit = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.comboBox_City = new System.Windows.Forms.ComboBox(); this.label_City = new System.Windows.Forms.Label(); this.txt_Weather1 = new System.Windows.Forms.Label(); this.txt_Date1 = new System.Windows.Forms.Label(); this.txt_Temp1 = new System.Windows.Forms.Label(); this.txt_WindPower1 = new System.Windows.Forms.Label(); this.txt_Temp2 = new System.Windows.Forms.Label(); this.txt_WindPower2 = new System.Windows.Forms.Label(); this.txt_Date2 = new System.Windows.Forms.Label(); this.txt_Weather2 = new System.Windows.Forms.Label(); this.timer1 = new System.Windows.Forms.Timer();
// // mainMenu1 //
this.mainMenu1.MenuItems.Add(this.menuItem1); this.mainMenu1.MenuItems.Add(this.menuItem_Menu); // // menuItem1 //
this.menuItem1.Text = "确定"; this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
// // menuItem_Menu //
this.menuItem_Menu.MenuItems.Add(this.menuItem_Exit); this.menuItem_Menu.MenuItems.Add(this.menuItem3); this.menuItem_Menu.MenuItems.Add(this.menuItem2); this.menuItem_Menu.Text = "菜单";
// // menuItem_Exit //
this.menuItem_Exit.Text = "退出"; this.menuItem_Exit.Click += new System.EventHandler(this.menuItem_Exit_Click);
// // menuItem3 //
this.menuItem3.Text = "-";
// // menuItem2 //
this.menuItem2.Text = "关于"; this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
// // comboBox_City //
this.comboBox_City.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Regular); this.comboBox_City.Location = new System.Drawing.Point(52, 8); this.comboBox_City.Size = new System.Drawing.Size(114, 22);
// // label_City //
this.label_City.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Bold); this.label_City.Location = new System.Drawing.Point(4, 12); this.label_City.Size = new System.Drawing.Size(52, 16); this.label_City.Text = "城市:"; this.label_City.TextAlign = System.Drawing.ContentAlignment.TopCenter;
// // txt_Weather1 //
this.txt_Weather1.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Regular); this.txt_Weather1.Location = new System.Drawing.Point(12, 50); this.txt_Weather1.Size = new System.Drawing.Size(152, 14); this.txt_Weather1.Text = "天气:";
// // txt_Date1 //
this.txt_Date1.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Regular); this.txt_Date1.Location = new System.Drawing.Point(12, 34); this.txt_Date1.Size = new System.Drawing.Size(152, 14); this.txt_Date1.Text = "日期:";
// // txt_Temp1 //
this.txt_Temp1.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Regular); this.txt_Temp1.Location = new System.Drawing.Point(12, 68); this.txt_Temp1.Size = new System.Drawing.Size(152, 14); this.txt_Temp1.Text = "气温:";
// // txt_WindPower1 //
this.txt_WindPower1.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Regular); this.txt_WindPower1.Location = new System.Drawing.Point(12, 84); this.txt_WindPower1.Size = new System.Drawing.Size(152, 14); this.txt_WindPower1.Text = "风力:";
// // txt_Temp2 //
this.txt_Temp2.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Regular); this.txt_Temp2.Location = new System.Drawing.Point(12, 140); this.txt_Temp2.Size = new System.Drawing.Size(152, 14); this.txt_Temp2.Text = "气温:";
// // txt_WindPower2 //
this.txt_WindPower2.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Regular); this.txt_WindPower2.Location = new System.Drawing.Point(12, 156); this.txt_WindPower2.Size = new System.Drawing.Size(152, 14); this.txt_WindPower2.Text = "风力:";
// // txt_Date2 //
this.txt_Date2.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Regular); this.txt_Date2.Location = new System.Drawing.Point(12, 108); this.txt_Date2.Size = new System.Drawing.Size(152, 14); this.txt_Date2.Text = "日期:";
// // txt_Weather2 //
this.txt_Weather2.Font = new System.Drawing.Font("Nina", 9F, System.Drawing.FontStyle.Regular); this.txt_Weather2.Location = new System.Drawing.Point(12, 124); this.txt_Weather2.Size = new System.Drawing.Size(152, 14); this.txt_Weather2.Text = "天气:";
// // timer1 //
this.timer1.Interval = 200; this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
// // MainForm //
this.Controls.Add(this.comboBox_City); this.Controls.Add(this.txt_Date1); this.Controls.Add(this.txt_Weather1); this.Controls.Add(this.label_City); this.Controls.Add(this.txt_Temp1); this.Controls.Add(this.txt_WindPower1); this.Controls.Add(this.txt_Temp2); this.Controls.Add(this.txt_WindPower2); this.Controls.Add(this.txt_Date2); this.Controls.Add(this.txt_Weather2); this.Menu = this.mainMenu1; this.Text = "天气预报"; }
#endregion
/// <summary> /// The main entry point for the application. /// </summary>
static void Main() { Application.Run(new MainForm()); }
private void menuItem_Exit_Click(object sender, System.EventArgs e) { this.Dispose(); }
private void menuItem1_Click(object sender, System.EventArgs e) { SearchWeather(this.comboBox_City.Text); }
private string[] myString = new string[] { "日期: ", "温度: ", "天气: ", "风力: ", };
public void SearchWeather(string cityName) { if( this.txt_Date1.Text != myString[0] ) { ReSelect(); }
this.Text = "正在下载..."; this.timer1.Enabled = true;
WeatherService.Weather weather = new WeatherService.Weather(); DataSet myDs = weather.GetWeatherDataSet(cityName);
this.txt_Date1.Text = myString[0] + myDs.Tables[0].Rows[0]["Date1"].ToString(); this.txt_Temp1.Text = myString[1] + myDs.Tables[0].Rows[0]["Temp1"].ToString(); this.txt_Weather1.Text = myString[2] + myDs.Tables[0].Rows[0]["Weather1"].ToString(); this.txt_WindPower1.Text = myString[3] + myDs.Tables[0].Rows[0]["WindPower1"].ToString();
this.txt_Date2.Text = myString[0] + myDs.Tables[0].Rows[0]["Date2"].ToString(); this.txt_Temp2.Text = myString[1] + myDs.Tables[0].Rows[0]["Temp2"].ToString(); this.txt_Weather2.Text = myString[2] + myDs.Tables[0].Rows[0]["Weather2"].ToString(); this.txt_WindPower2.Text = myString[3] + myDs.Tables[0].Rows[0]["WindPower2"].ToString(); }
private void ReSelect() { this.txt_Date1.Text = myString[0]; this.txt_Temp1.Text = myString[1]; this.txt_Weather1.Text = myString[2]; this.txt_WindPower1.Text = myString[3]; this.txt_Date2.Text = myString[0]; this.txt_Temp2.Text = myString[1]; this.txt_Weather2.Text = myString[2]; this.txt_WindPower2.Text = myString[3]; }
private void timer1_Tick(object sender, System.EventArgs e) { if( this.txt_Date1.Text.IndexOf("月") != -1) { this.timer1.Enabled = false; this.Text = "天气预报"; } }
private void menuItem2_Click(object sender, System.EventArgs e) { this.Text = "作者:贺星河"; System.Threading.Thread.Sleep(3000); this.Text = "天气预报"; } } } |
四、在多普达565手机上部署并运行
1、在VS.NET2003的“解决方案WeatherService”上点击右键,选择”部署解决方案”,出现一下对话框
图4-部署解决方案 |
选择“部署”,“部署”完成后,手机上将显示如下界面
图5、手机界面之一-部署 |
因为我的PC机器上安装了.NET Framework1.1SP1,所以会提示这个界面,选择“确定”,继续执行安装部署:
图6、手机界面之二-选择安装位置 |
选择安装位置为”Sotrage Card”,选择“完成”,这个时候程序就部署完毕了,
使用Resco Explore 2003,找到安装部署后程序所在的目录,在 \Sorage\Program Files\WeatherService\ 目录下面,执行程序WeatherService.exe,将出现如下画面:
图7、手机界面之三-开始执行程序 选择“是”。 |
之所以出现这个画面,是因为程序没有经过系统的认证,也是微软安全方面的一个体现,即时这个程序会正常执行,也不会冒然打出电话!
程序执行之后,会出现如下画面,选择需要查询的城市名称,点“确定”
图8、手机界面之四-程序界面 |
之后程序标题会变为“正在下载…”,程序通过GPRS上网读取部署在Internet上的WebService
图9、手机界面之五-运行界面 |
稍等几秒钟之后,便会看到所需要的天气信息数据
图10、手机界面之六-运行结果 |