最近做了一个简单的天气预报,话不多说上代码
实时天气的handler:
四天内天气的handler
activity
发送天气
[quote]package com.weather;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.telephony.SmsManager;
/**
* 发送短信界面
* @author wdw
*
*/
public class SendWeather extends Activity {
private EditText editNumber;
private EditText messagEditText;
private String weatherString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showDialog();
//得到数据
try {
Bundle bundle = this.getIntent().getExtras();
weatherString=bundle.getString("weather");
messagEditText.setText(weatherString);
} catch (Exception e) {
e.printStackTrace();
}
editNumber.requestFocus();
}
/**检查字符串是否为电话号码的格式*/
public static boolean isPhoneNumberValid(String phoneNumber)
{
// boolean isValid=false;
// String expression="^\\(?(\\d{3})\\)?[- ]?(?(\\d{3})\\)?[- ]?(\\d{5})$";
// String expression2="^\\(?(\\d{3})\\)?[- ]?(?(\\d{4})\\)?[- ]?(\\d{4})$";
// CharSequence inputStr=phoneNumber;
// /*创建pattern*/
// Pattern pattern=Pattern.compile(expression);
// /*将pattern以参数传入Matcher*/
// Matcher matcher=pattern.matcher(inputStr);
// Pattern pattern2=Pattern.compile(expression2);
// Matcher matcher2=pattern2.matcher(inputStr);
// if(matcher.matches()||matcher2.matches())
// {
// isValid=true;
// }
return true;
}
//弹出框
public void showDialog()
{
LayoutInflater factory = LayoutInflater.from(this);
final View view = factory.inflate(R.layout.send_weather, null);
LinearLayout layout=(LinearLayout)view.findViewById(R.id.sendWeather);
editNumber=(EditText)layout.findViewById(R.id.numberEdit);
messagEditText=(EditText)layout.findViewById(R.id.weatherEdit);
new AlertDialog.Builder(this).setTitle("发送温情").setView(view)
.setPositiveButton("发送", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
//取得短信收件人电话
String number = editNumber.getText().toString();
//取得短信内容
String message = messagEditText.getText().toString();
/*构建default 的instance的SmsManager*/
SmsManager smsManager =SmsManager.getDefault();
/*检查电话格式与短信字数是否超过70个字符*/
if(number.equals("")) {
Toast.makeText(SendWeather.this, "请输入发送号码!", Toast.LENGTH_LONG).show();
onCreate(null);
return;
} else
{
if(isPhoneNumberValid(number)==true&&isWithin(message)==true)
{
try
{
PendingIntent pendingIntent =PendingIntent.getBroadcast(SendWeather.this, 0, new Intent(),0);
smsManager.sendTextMessage(number, null, message,pendingIntent , null);
}
catch(Exception e)
{
e.printStackTrace();
}
// Toast.makeText(NoteActivity.this, "发送成功!", Toast.LENGTH_LONG).show();
// Intent intent = new Intent(NoteActivity.this,MyNote.class);
// startActivity(intent);
finish();
}
else{
if(isPhoneNumberValid(number)==false)
{
if(isWithin(message)==false)
{
Toast.makeText(SendWeather.this,
"电话号码格式错误和短信内容超过70字请检查!", Toast.LENGTH_LONG).show();
onCreate(null);
}
else{
Toast.makeText(SendWeather.this,
"电话号码格式错误请检查!", Toast.LENGTH_LONG).show();
onCreate(null);
}
}
else if(isWithin(message)==false)
{
Toast.makeText(SendWeather.this,
"短信内容超过70字请删除部分内容!", Toast.LENGTH_LONG).show();
onCreate(null);
}
}
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
// Intent intent = new Intent(NoteActivity.this,MyNote.class);
// startActivity(intent);
finish();
}
}).show();
}
/**判断短信长度*/
public static boolean isWithin(String text)
{
if(text.length()<=70)
{
return true;
}
else{
return false;
}
}
/**结束*/
public void finish()
{
super.finish();
}
}
[/quote]
实时天气的handler:
package com.handler;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.javaBean.Weather;
/**
* 显示当天的详细天气情况
* @author wdw
*
*/
public class NonceXmlHandler extends DefaultHandler
{
private List<Weather>nowWeatherList;
private boolean tag;
private Weather weather;
public List<Weather> getNowWeatherList()
{
return nowWeatherList;
}
public void setNowWeatherList(List<Weather> nowWeatherList)
{
this.nowWeatherList = nowWeatherList;
}
//构造方法
public NonceXmlHandler()
{
nowWeatherList = new ArrayList<Weather>();
tag = false;
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException
{
String tagName = localName.length()!=0 ? localName : name;
tagName = tagName.toLowerCase();
if (tagName.equals("current_conditions"))
{
tag = true;
weather = new Weather();
}
if (tag)
{
if (tagName.equals("temp_c"))
{
weather.setLowTemp(attributes.getValue("data"));
}
else if (tagName.equals("temp_f"))
{
weather.setHighTemp(attributes.getValue("data"));
}
else if (tagName.equals("icon"))
{
weather.setImgUrl(attributes.getValue("data"));
}
else if (tagName.equals("condition"))
{
weather.setCircs(attributes.getValue("data"));
}
else if (tagName.equals("wind_condition"))
{
weather.setWind(attributes.getValue("data"));
}
else if (tagName.equals("humidity"))
{
weather.setHumidity(attributes.getValue("data"));
}
}
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
String tagName = localName.length()!=0 ? localName : name;
tagName = tagName.toLowerCase();
if(tagName.equals("current_conditions"))
{
tag = false;
nowWeatherList.add(weather);
}
super.endElement(uri, localName, name);
}
}
四天内天气的handler
package com.handler;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.javaBean.Weather;
/**
*
* @author wdw
*
*/
public class XmlHandler extends DefaultHandler{
private List<Weather>weatherList;
private boolean tag;
private Weather weather;
//list的get/set方法
public List<Weather> getWeatherList() {
return weatherList;
}
public void setWeatherList(List<Weather> weatherList) {
this.weatherList = weatherList;
}
//构造方法
public XmlHandler()
{
weatherList = new ArrayList<Weather>();
tag = false;
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
String tagName = localName.length()!=0 ? localName : name;
tagName = tagName.toLowerCase();
if (tagName.equals("forecast_conditions")) {
tag = true;
weather = new Weather();
}
if (tag)
{
if (tagName.equals("day_of_week"))
{
weather.setDayString(attributes.getValue("data"));
}
else if (tagName.equals("low"))
{
weather.setLowTemp(attributes.getValue("data"));
}
else if (tagName.equals("high"))
{
weather.setHighTemp(attributes.getValue("data"));
}
else if (tagName.equals("icon"))
{
weather.setImgUrl(attributes.getValue("data"));
}
else if (tagName.equals("condition"))
{
weather.setCircs(attributes.getValue("data"));
}
else if (tagName.equals("wind_condition"))
{
weather.setWind(attributes.getValue("data"));
}
}
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
String tagName = localName.length()!=0 ? localName : name;
tagName = tagName.toLowerCase();
if(tagName.equals("forecast_conditions"))
{
tag = false;
weatherList.add(weather);
}
}
}
activity
package com.weather;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import com.database.WeatherDAO;
import com.handler.NonceXmlHandler;
import com.handler.XmlHandler;
import com.javaBean.Weather;
import com.util.LunarCalendarUtils;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
/**
*
* @author wdw
*
*/
public class WeatherActivity extends Activity {
private Spinner selectCity;
private EditText inputCity;
private Button onSure;
private TextView showCity;
private ImageView weaView;
private Handler weatherHandler;
private Dialog progressDialog;
private Timer timer;
public static final String STR_DESKTOP_TO_APP_EXPAND = "DESKTOP_TO_APP_FLAG_EXPAND";
public static final String STR_DESKTOP_TO_APP_ID = "DESKTOP_TO_APP_FLAG_ID";
public static final String STR_DESKTOP_TO_APP_TYPE = "DESKTOP_TO_APP_FLAG_TYPE";
private Intent myIntent;
private final String ACTION_ADD_SHORTCUT="com.android.launcher.action.INSTALL_SHORTCUT";
private String weatherStr;
private final int MENU_SENDTOP=Menu.FIRST;
private final int MENU_EXIT=Menu.FIRST+1;
private WeatherDAO weatherDAO;
private Cursor myCursor;
private TableLayout table;
private LunarCalendarUtils calendarUtils;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myIntent = new Intent(this,SendWeather.class);
weatherDAO = new WeatherDAO(this);
timer = new Timer();
selectCity = (Spinner)findViewById(R.id.weaSpCity);
inputCity = (EditText)findViewById(R.id.weaEtCity);
onSure = (Button)findViewById(R.id.weaBtSearch);
showCity = (TextView)findViewById(R.id.weaTvCity);
weaView = (ImageView)findViewById(R.id.weaIv);
progressDialog = new AlertDialog.Builder(this)
.setTitle("读取数据中")
.setMessage("正在加载数据,请稍等!")
.create();
weatherHandler = new Handler()
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
final String cityName = inputCity.getText().toString();
searchWeather(cityName);
searchNowWeather(cityName);
progressDialog.hide();
}
};
selectCity.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
inputCity.setText(selectCity.getSelectedItem().toString());
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
onSure.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
progressDialog.show();
timer.schedule(new TimerTask(){
@Override
public void run() {
Message message = new Message();
message.setTarget(weatherHandler);
message.sendToTarget();
}
}, 100);
}
});
showCity.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
searchNowWeather(inputCity.getText().toString());
goTO();
}
});
}
/**创建menu*/
@Override
/*创建menu*/
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_SENDTOP, 1, "发送快捷方式").setIcon(android.R.drawable.ic_menu_share);
menu.add(0,MENU_EXIT,2,"返回桌面").setIcon(android.R.drawable.ic_menu_revert);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SENDTOP:
searchNowWeather(inputCity.getText().toString());
weatherStr=showCity.getText().toString();
Parcelable icon =Intent.ShortcutIconResource.fromContext(this, R.drawable.weather);
Intent addShortCut = new Intent(ACTION_ADD_SHORTCUT);
addShortCut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
addShortCut.putExtra(Intent.EXTRA_SHORTCUT_NAME, weatherStr);
myIntent.setData(Uri.parse(weatherStr));
Bundle bundle = new Bundle();
bundle.putString("weather", weatherStr);
myIntent.putExtras(bundle);
addShortCut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
myIntent);
sendBroadcast(addShortCut);
goTO();
break;
case MENU_EXIT:
goTO();
finish();
break;
}
return super.onOptionsItemSelected(item);
}
/**查询当天天气*/
public void searchNowWeather(String city)
{
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sParser = spf.newSAXParser();
XMLReader reader = sParser.getXMLReader();
NonceXmlHandler nowHandler = new NonceXmlHandler();
reader.setContentHandler(nowHandler);
URL url = new URL("http://www.google.com/ig/api?hl=zh-cn&weather="+URLEncoder.encode(city));
InputStream iStream = url.openStream();
InputStreamReader isr = new InputStreamReader(iStream,"GBK");
InputSource source = new InputSource(isr);
reader.parse(source);
List<Weather> weatherList = nowHandler.getNowWeatherList();
for (Weather weather:weatherList)
{
weaView.setImageDrawable(loadImage(weather.getImgUrl()));
weaView.setMinimumHeight(80);
String strLine = System.getProperty("line.separator");
showCity.setText(inputCity.getText().toString()+"实时天气:"
+strLine+weather.getLowTemp() + "℃"
+" 、 "+weather.getCircs()
+strLine+weather.getWind()
+strLine+weather.getHumidity());
}
weatherStr = showCity.getText().toString();
} catch (Exception e) {
new AlertDialog.Builder(this)
.setTitle("解析错误")
.setMessage("获取当天天气数据失败,请稍候再试。")
.setNegativeButton("确定", null)
.show();
}
}
/**查询四天内的天气*/
public void searchWeather(String city)
{
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
XMLReader reader = sp.getXMLReader();
XmlHandler handler = new XmlHandler();
reader.setContentHandler(handler);
URL url = new URL("http://www.google.com/ig/api?hl=zh-cn&weather=" + URLEncoder.encode(city));
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is,"GBK");
InputSource source = new InputSource(isr);
reader.parse(source);
List<Weather> weatherList = handler.getWeatherList();
table = (TableLayout)findViewById(R.id.weaTable);
table.removeAllViews();
for(Weather weather : weatherList) {
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
row.setGravity(Gravity.CENTER_VERTICAL);
ImageView img = new ImageView(this);
img.setImageDrawable(loadImage(weather.getImgUrl()));
img.setMinimumHeight(80);
row.addView(img);
TextView day = new TextView(this);
day.setText(weather.getDayString());
day.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(day);
TextView temp = new TextView(this);
temp.setText(weather.getLowTemp() + "℃ - " + weather.getHighTemp() + "℃");
temp.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(temp);
TextView condition = new TextView(this);
condition.setText(weather.getCircs());
condition.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(condition);
TextView wind = new TextView(this);
wind.setText(weather.getWind());
wind.setGravity(Gravity.CENTER_VERTICAL);
row.addView(wind);
table.addView(row);
}
} catch (Exception e) {
new AlertDialog.Builder(this)
.setTitle("解析错误")
.setMessage("获取天气数据失败,请稍候再试。")
.setNegativeButton("确定", null)
.show();
}
}
//加载天气图片
private Drawable loadImage(String imgUrl) {
try {
return Drawable.createFromStream((InputStream) new URL("http://www.google.com/" + imgUrl).getContent(), "demo");
}catch (MalformedURLException e) {
Log.e("exce",e.getMessage());
}
catch (Exception e) {
Log.e("exce", e.getMessage());
}
return null;
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
goTO();
}
//发送快捷方式
public void goTO()
{
searchNowWeather(inputCity.getText().toString());
weatherStr=showCity.getText().toString();
Intent intent = new Intent("com.android.CLICK");
Bundle bundle1 =new Bundle();
bundle1.putString("weather", weatherStr);
intent.putExtras(bundle1);
WeatherActivity.this.sendBroadcast(intent);
}
//插入天气
public void insert()
{
weatherDAO.weatherInsert(weatherStr, table.toString());
}
//更新天气
public void update(int id,String timeString,String todayString)
{
weatherDAO.updateWeather(id, timeString, todayString);
}
}
发送天气
[quote]package com.weather;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.telephony.SmsManager;
/**
* 发送短信界面
* @author wdw
*
*/
public class SendWeather extends Activity {
private EditText editNumber;
private EditText messagEditText;
private String weatherString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showDialog();
//得到数据
try {
Bundle bundle = this.getIntent().getExtras();
weatherString=bundle.getString("weather");
messagEditText.setText(weatherString);
} catch (Exception e) {
e.printStackTrace();
}
editNumber.requestFocus();
}
/**检查字符串是否为电话号码的格式*/
public static boolean isPhoneNumberValid(String phoneNumber)
{
// boolean isValid=false;
// String expression="^\\(?(\\d{3})\\)?[- ]?(?(\\d{3})\\)?[- ]?(\\d{5})$";
// String expression2="^\\(?(\\d{3})\\)?[- ]?(?(\\d{4})\\)?[- ]?(\\d{4})$";
// CharSequence inputStr=phoneNumber;
// /*创建pattern*/
// Pattern pattern=Pattern.compile(expression);
// /*将pattern以参数传入Matcher*/
// Matcher matcher=pattern.matcher(inputStr);
// Pattern pattern2=Pattern.compile(expression2);
// Matcher matcher2=pattern2.matcher(inputStr);
// if(matcher.matches()||matcher2.matches())
// {
// isValid=true;
// }
return true;
}
//弹出框
public void showDialog()
{
LayoutInflater factory = LayoutInflater.from(this);
final View view = factory.inflate(R.layout.send_weather, null);
LinearLayout layout=(LinearLayout)view.findViewById(R.id.sendWeather);
editNumber=(EditText)layout.findViewById(R.id.numberEdit);
messagEditText=(EditText)layout.findViewById(R.id.weatherEdit);
new AlertDialog.Builder(this).setTitle("发送温情").setView(view)
.setPositiveButton("发送", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
//取得短信收件人电话
String number = editNumber.getText().toString();
//取得短信内容
String message = messagEditText.getText().toString();
/*构建default 的instance的SmsManager*/
SmsManager smsManager =SmsManager.getDefault();
/*检查电话格式与短信字数是否超过70个字符*/
if(number.equals("")) {
Toast.makeText(SendWeather.this, "请输入发送号码!", Toast.LENGTH_LONG).show();
onCreate(null);
return;
} else
{
if(isPhoneNumberValid(number)==true&&isWithin(message)==true)
{
try
{
PendingIntent pendingIntent =PendingIntent.getBroadcast(SendWeather.this, 0, new Intent(),0);
smsManager.sendTextMessage(number, null, message,pendingIntent , null);
}
catch(Exception e)
{
e.printStackTrace();
}
// Toast.makeText(NoteActivity.this, "发送成功!", Toast.LENGTH_LONG).show();
// Intent intent = new Intent(NoteActivity.this,MyNote.class);
// startActivity(intent);
finish();
}
else{
if(isPhoneNumberValid(number)==false)
{
if(isWithin(message)==false)
{
Toast.makeText(SendWeather.this,
"电话号码格式错误和短信内容超过70字请检查!", Toast.LENGTH_LONG).show();
onCreate(null);
}
else{
Toast.makeText(SendWeather.this,
"电话号码格式错误请检查!", Toast.LENGTH_LONG).show();
onCreate(null);
}
}
else if(isWithin(message)==false)
{
Toast.makeText(SendWeather.this,
"短信内容超过70字请删除部分内容!", Toast.LENGTH_LONG).show();
onCreate(null);
}
}
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
// Intent intent = new Intent(NoteActivity.this,MyNote.class);
// startActivity(intent);
finish();
}
}).show();
}
/**判断短信长度*/
public static boolean isWithin(String text)
{
if(text.length()<=70)
{
return true;
}
else{
return false;
}
}
/**结束*/
public void finish()
{
super.finish();
}
}
[/quote]