Android 编程之天气预报小实例源码演示及效果展示--2

上一篇博客我们把权限和欢迎动画讲了一下,接下来给大家讲服务和主活动的使用,在上一篇中我们介绍到了服务和活动,在

启动服务之后,服务会将网络请求到的天气信息以广播的形式发送至活动,而活动只需要接收广播就OK了,之后将得到的数据

赋给对应的容器组件就OK了

下面我们先来看看服务的代码 (extends IntentService implements LocationListener):

package com.newer.myweather;
/**
 * 天气情况信息服务
 * @author Engineer-Jsp
 * @date 2014.10.27
 * */
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.newer.myweather.API.WeatherApi;
import com.newer.myweather.entity.Forecast;
import com.newer.myweather.entity.ForecastTen;
import com.newer.myweather.entity.WeatherInfo;

import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;

public class WeatherService extends IntentService implements LocationListener {

	public static final String EXTRA_CITY_NAME = "city_name";
	private static final String TAG = "XXXXXXXXXXXXXX";
	public static final String EXTRA_WEATHER_INFO = "weather_info";
	public static final String EXTRA_4_DAY = "4_day";
	public static final String EXTRA_10_DAY = "10_day";
	public static String[] infos;

	private Location location;
	private LocationManager locationManager;

	public static String city;
	public static String l;
	private SurfaceView surfaceView;

	private WeatherInfo weatherInfo;
	private ArrayList<Forecast> forecast4Day;
	private ArrayList<ForecastTen> forecast10Day;

	public WeatherService() {
		super("WeatherService");
		weatherInfo = new WeatherInfo();
		forecast4Day = new ArrayList<Forecast>();
		forecast10Day = new ArrayList<ForecastTen>();
	}

	@Override
	public void onCreate() {
		super.onCreate();
        // 地理位置管理
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		location = locationManager
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 0, 0, this);

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		locationManager.removeUpdates(this);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// 子线程中执行
		// 发送网络请求
		if (location != null) {
			// 纬度
			double lat = location.getLatitude();
			// 经度
			double lon = location.getLongitude();

			try {
				// 28.13725106,112.99305086/长沙
				getCity(lat, lon);
				Log.d("XXXXXXXXXXXXXX", "纬度:"+lat+"  "+"经度:"+lon);
				getCondition(l);
				Log.d("XXXXXXXXXXXXXX", "城市:"+l);
				getForecast();
				getForecastTen();

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

		// 存储数据

		// 发送广播
		Intent result = new Intent("com.newer.uweather.ACTION_UPDATE_DATA");

		result.putExtra(EXTRA_WEATHER_INFO, weatherInfo);
		result.putExtra(EXTRA_4_DAY, forecast4Day);
		result.putExtra(EXTRA_10_DAY, forecast10Day);
		sendBroadcast(result);

	}
    // 获取未来10天的天气数据
	private void getForecastTen() throws ClientProtocolException, IOException,
			JSONException {

		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(WeatherApi.URL_10DAYS);
		HttpResponse response = client.execute(get);

		if (response.getStatusLine().getStatusCode() == 200) {
			String json = EntityUtils.toString(response.getEntity(), "utf8");

			JSONObject root = new JSONObject(json);
			JSONObject forecast = root.getJSONObject("forecast");
			JSONObject simpleforecast = forecast
					.getJSONObject("simpleforecast");
			JSONArray forecastday = simpleforecast.getJSONArray("forecastday");

			for (int i = 0; i < forecastday.length(); i++) {
				JSONObject item = (JSONObject) forecastday.get(i);
				JSONObject date = item.getJSONObject("date");
				int day = date.getInt("day");
				int month = date.getInt("month");
				String weekday_short = date.getString("weekday_short");

				JSONObject high = item.getJSONObject("high");
				String highCelsius = high.getString("celsius");
				JSONObject low = item.getJSONObject("low");
				String lowCelsius = low.getString("celsius");
				int avehumidity = item.getInt("avehumidity");
				String iconUrl = item.getString("icon_url");

				ForecastTen f = new ForecastTen();

				f.setDay(day);
				f.setAvehumidity(avehumidity);
				f.setHighCelsius(highCelsius);
				f.setIconUrl(iconUrl);
				f.setLowCelsius(lowCelsius);
				f.setMonth(month);
				f.setWeekday_short(weekday_short);
				f.setIconUrl(iconUrl);

				forecast10Day.add(f);
				Log.d(TAG, "获取最近10天的天气情况:\n" + forecast10Day.toString());
			}
		} else {
			Log.d(TAG, "获取失败");
		}

	}
	// 获取未来4天的天气数据
	private void getForecast() throws ClientProtocolException, IOException,
			JSONException {

		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(WeatherApi.URL_4DAYS);
		HttpResponse response = client.execute(get);

		if (response.getStatusLine().getStatusCode() == 200) {
			String json = EntityUtils.toString(response.getEntity(), "utf8");

			JSONObject root = new JSONObject(json);
			JSONObject forecast = root.getJSONObject("forecast");
			JSONObject txtForecast = forecast.getJSONObject("txt_forecast");
			JSONArray forecastday = txtForecast.getJSONArray("forecastday");

			for (int i = 0; i < forecastday.length(); i++) {
				JSONObject item = (JSONObject) forecastday.get(i);

				String title = item.getString("title");
				String iconUrl = item.getString("icon_url");
				String fcttextMetric = item.getString("fcttext_metric");
				infos = fcttextMetric.split("。");
				Log.d(TAG, infos.length + ", " + Arrays.toString(infos));

				Forecast f = new Forecast();
				f.setDate(title);
				f.setIconUrl(iconUrl);

				f.setTempC(infos[1]);
				f.setWind(infos[2]);

				if (infos.length == 4) {
					f.setHumidity(infos[3].substring(6));
				} else {
					f.setHumidity("无");
				}

				Log.d(TAG, "Forecast" + f.toString());

				if (i % 2 == 0) {
					forecast4Day.add(f);
				}
				Log.d(TAG, "获取最近4天的天气情况:\n" + forecast4Day.toString());
			}
		} else {
			Log.d(TAG, "获取失败");
		}

	}
    //长沙城市天气信息  http://api.wunderground.com/api/您的key/conditions/lang:CN/q/zmw:00000.1.57679.json
	private void getCondition(String cityInfo) throws ClientProtocolException,
			IOException, JSONException {

		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(WeatherApi.URL_CONDITIONS + cityInfo
				+ ".json");
		HttpResponse response = client.execute(get);

		if (response.getStatusLine().getStatusCode() == 200) {
			String json = EntityUtils.toString(response.getEntity(), "utf8");
			Log.d(TAG,
					"//---------------------------------------------------------");
			Log.d(TAG, json);

			JSONObject object = new JSONObject(json);
			JSONObject condition = object.getJSONObject("current_observation");

			String weather = condition.getString("weather");
			int tempC = condition.getInt("temp_c");
			String humidity = condition.getString("relative_humidity");
			String wind_dir = condition.getString("wind_dir");
			String iconUrl = condition.getString("icon_url");

			weatherInfo.setWeather(weather);
			weatherInfo.setTempC(tempC);
			weatherInfo.setHumidity(humidity);
			weatherInfo.setWind_dir(wind_dir);
			weatherInfo.setIconUrl(iconUrl);

			Log.d(TAG, "获取实时天气情况:\n"+String.format("%d, %s, %s, %s", tempC, humidity,
					weather, wind_dir, iconUrl));
		} else {
			Log.d(TAG, "请求失败");
		}
	}
    //长沙天气示例  http://api.wunderground.com/api/<span style="font-family:Arial, Helvetica, sans-serif;">您的key</span>/geolookup/lang:CN/q/28.13725106,112.99305086.json
	private void getCity(double lat, double lon)
			throws ClientProtocolException, IOException, JSONException {

		HttpClient client = new DefaultHttpClient();
		StringBuffer buffer = new StringBuffer();
		buffer.append(lat).append(",").append(lon).append(".json");
		HttpGet get = new HttpGet(WeatherApi.URL_GEOLOOKUP + buffer);

		HttpResponse response = client.execute(get);

		if (response.getStatusLine().getStatusCode() == 200) {

			String json = EntityUtils.toString(response.getEntity(), "utf8");
			Log.d(TAG, "经纬度获取城市"+json);

			JSONObject object = new JSONObject(json);
			JSONObject jLocation = (JSONObject) object
					.getJSONObject("location");

			city = jLocation.getString("city");
			l = jLocation.getString("l");

			Log.d(TAG,"经纬度获取城市"+ String.format("%s, %s", city, l));

		} else {
			Log.d(TAG, "请求失败");
		}

	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		this.location = location;
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}
	
}

主活动代码:

package com.newer.myweather;
/**
 * 主活动界面
 * @author Enigneer-Jsp
 * @date 2014.10.27
 * */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.newer.myweather.entity.Forecast;
import com.newer.myweather.entity.ForecastTen;
import com.newer.myweather.entity.WeatherInfo;
import com.newer.myweather.weight.MyListView;
import com.newer.myweather.weight.MyListView.OnRefreshListener;
import com.squareup.picasso.Picasso;

import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
		OnNavigationListener {

	protected static final String TAG = "MainActivity-XXXXXXXXXX";

	SectionsPagerAdapter mSectionsPagerAdapter;

	ViewPager mViewPager;

	public static ArrayList<String> locations = new ArrayList<String>();

	static ForecastGridAdapter gridAdapter;
	static Hour48Adapter hour48Adapter;
	static FutureAdapter futureAdapter;

	private static ArrayList<Forecast> forecast4Day = new ArrayList<Forecast>();
	private static ArrayList<ForecastTen> forecast10Day = new ArrayList<ForecastTen>();
  
	static TextView currentTempC, currentWeather, currentHumidity, currentWind;
	static ImageView currentIcon;
	static TextView hour48TempC, hour48Date, hour48Humidity;
	static ImageView hour48Icon;
	static MyListView hour48ListView;
	WeatherInfo weatherInfo;
	// 注册广播
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@SuppressWarnings("unchecked")
		@Override
		public void onReceive(Context context, Intent intent) {

			Toast.makeText(getApplicationContext(), "更新数据", Toast.LENGTH_LONG)
					.show();
			invalidateOptionsMenu();
            // 接收广播
			weatherInfo = (WeatherInfo) intent
					.getSerializableExtra(WeatherService.EXTRA_WEATHER_INFO);

			Log.d(TAG, "实时城市天气信息:\n"+weatherInfo.toString());

			currentHumidity.setText("空气湿度: " + weatherInfo.getHumidity());
			currentTempC.setText(weatherInfo.getTempC() + "℃");
			currentWeather.setText(weatherInfo.getWeather());
			currentWind.setText("风力: " + weatherInfo.getWind_dir());
			Picasso.with(getApplicationContext())
					.load(weatherInfo.getIconUrl()).into(currentIcon);

			forecast4Day = (ArrayList<Forecast>) intent
					.getSerializableExtra(WeatherService.EXTRA_4_DAY);
			forecast10Day = (ArrayList<ForecastTen>) intent
					.getSerializableExtra(WeatherService.EXTRA_10_DAY);

			// 更新listView的状态
			hour48ListView.onRefreshComplete();

			Log.d(TAG, "最近4天的天气情况:\n" + forecast4Day.toString());
			Log.d(TAG, "最近10天的天气情况:\n" + forecast10Day.toString());
			gridAdapter.notifyDataSetChanged();
			hour48Adapter.notifyDataSetChanged();

		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);
		mViewPager.setCurrentItem(1);

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayShowTitleEnabled(false);

		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		//android.R.layout.simple_spinner_dropdown_item


		SpinnerAdapter adapter = new ArrayAdapter<String>(this,
		android.R.layout.simple_spinner_dropdown_item, locations);
		actionBar.setListNavigationCallbacks(adapter, this);

	}



	@Override
	protected void onStart() {
		super.onStart();
		// 首选项配置
		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		boolean net = preferences.getBoolean("net", false);
		if (net) {
			// 获取通知管理器
			NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			int icon = android.R.drawable.stat_notify_chat;
			long when = System.currentTimeMillis();
			// 新建一个通知,指定其图标和标题
			Notification notification = new Notification(icon, null, when);// 第一个参数为图标,第二个参数为短暂提示标题,第三个为通知时间
			notification.flags = Notification.FLAG_ONGOING_EVENT;
			// notification.defaults = Notification.DEFAULT_SOUND;//发出默认声音
			Intent openintent = new Intent(this, MainActivity.class);
			// 当点击消息时就会向系统发送openintent意图
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
					openintent, PendingIntent.FLAG_UPDATE_CURRENT);
			notification.setLatestEventInfo(this, "爱天气","温度",
					contentIntent);
			mNotificationManager.notify(0, notification);// 第一个参数为自定义的通知唯一标识
		} else {
			clearNotification();
		}
	}
	// 删除通知
	private void clearNotification() {
		// 启动后删除之前我们定义的通知
		NotificationManager mNotificationManager = (NotificationManager) this
				.getSystemService(NOTIFICATION_SERVICE);
		mNotificationManager.cancel(0);
	}

	@Override
	protected void onResume() {
		super.onResume();

		IntentFilter filter = new IntentFilter(
				"com.newer.uweather.ACTION_UPDATE_DATA");
		registerReceiver(receiver, filter);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.ic_action_refresh:
			// 更新数据
			Intent intent = new Intent(this, WeatherService.class);
			startService(intent);

			// 显示进度
			item.setActionView(new ProgressBar(this, null,
					android.R.attr.progressBarStyle));
			item.expandActionView();

			return true;
		case R.id.ic_action_place:
			startActivity(new Intent(getApplicationContext(),
					LocationActivity.class));

			Toast.makeText(this, "定位", 0).show();
			break;
		case R.id.action_settings:
			Intent intentSettings = new Intent(this, SettingsActivity.class);
			startActivity(intentSettings);
			break;

		}

		return super.onOptionsItemSelected(item);
	}

	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {

			switch (position) {
			case 0:
				Hour48Fragment hour48Fragment = new Hour48Fragment();
				return hour48Fragment;
			case 1:
				CurrentFragment currentFragment = new CurrentFragment();
				return currentFragment;
			case 2:
				FutureFragment futureFragment = new FutureFragment();
				return futureFragment;

			}
			return null;
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			case 2:
				return getString(R.string.title_section3).toUpperCase(l);
			}
			return null;
		}
	}

	public static class CurrentFragment extends Fragment {

		private GridView gridView;

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			gridAdapter = new ForecastGridAdapter(getActivity(), forecast4Day);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main_current,
					container, false);

			currentHumidity = (TextView) rootView
					.findViewById(R.id.current_humidity);
			currentTempC = (TextView) rootView.findViewById(R.id.current_tempc);
			currentWeather = (TextView) rootView
					.findViewById(R.id.current_weather);
			currentWind = (TextView) rootView.findViewById(R.id.current_wind);
			currentIcon = (ImageView) rootView.findViewById(R.id.current_Icon);
			gridView = (GridView) rootView.findViewById(R.id.grid);
			gridView.setAdapter(gridAdapter);
			return rootView;
		}
	}

	/**
	 * 当前天气适配器
	 * 
	 * @author MaoZhua
	 * 
	 */
	public static class ForecastGridAdapter extends BaseAdapter {

		private ArrayList<Forecast> dataSet;
		private LayoutInflater inflater;
		private Context context;

		public ForecastGridAdapter(Context context,
				ArrayList<Forecast> forecast4Day) {
			this.context = context;
			dataSet = forecast4Day;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return dataSet.size();
		}

		@Override
		public Forecast getItem(int position) {
			return dataSet.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		static class ViewHolder {
			TextView date;
			TextView tempC;
			TextView wind;
			TextView hum;
			ImageView icon;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(
						R.layout.fragment_main_current_item, null);
				holder = new ViewHolder();

				holder.date = (TextView) convertView.findViewById(R.id.date);
				holder.tempC = (TextView) convertView.findViewById(R.id.tempc);
				holder.wind = (TextView) convertView.findViewById(R.id.wind);
				holder.hum = (TextView) convertView.findViewById(R.id.humidity);
				holder.icon = (ImageView) convertView.findViewById(R.id.icon);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			Forecast forecast = forecast4Day.get(position);

			holder.date.setText(forecast.getDate());
			holder.tempC.setText(forecast.getTempC().substring(6, 8) + "℃");
			holder.wind.setText(forecast.getWind().substring(0, 3) + "风");
			if (WeatherService.infos.length == 4) {
				holder.hum.setText(forecast.getHumidity());
			} else {
				holder.hum.setText("无");
			}

			// 第三方库: 毕加索
			Picasso.with(context).load(forecast.getIconUrl()).into(holder.icon);

			return convertView;
		}

	}

	/**
	 * 48小时
	 * 
	 * @author MaoZhua
	 * 
	 */
	public static class Hour48Adapter extends BaseAdapter {

		private ArrayList<Forecast> dataSet;
		private LayoutInflater inflater;
		private Context context;

		public Hour48Adapter(Context context, ArrayList<Forecast> forecast4Day) {
			this.context = context;
			dataSet = forecast4Day;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return dataSet.size();
		}

		@Override
		public Forecast getItem(int position) {
			return dataSet.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		static class ViewHolder {
			TextView date;
			TextView tempC;
			TextView wind;
			TextView hum;
			ImageView icon;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(
						R.layout.fragment_main_hour48_item, null);
				holder = new ViewHolder();

				holder.date = (TextView) convertView
						.findViewById(R.id.hour48_date);
				holder.tempC = (TextView) convertView
						.findViewById(R.id.hour48_temp);
				holder.hum = (TextView) convertView
						.findViewById(R.id.hour48_humidity);
				holder.icon = (ImageView) convertView
						.findViewById(R.id.hour48_icon);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			Forecast forecast = forecast4Day.get(position);

			holder.date.setText(forecast.getDate());
			holder.tempC.setText(forecast.getTempC().substring(6, 8) + "℃");
			if (WeatherService.infos.length == 4) {
				holder.hum.setText(forecast.getHumidity());
			} else {
				holder.hum.setText("无");
			}

			// 第三方库: 毕加索
			Picasso.with(context).load(forecast.getIconUrl()).into(holder.icon);

			return convertView;
		}

	}

	public static class Hour48Fragment extends Fragment {
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			hour48Adapter = new Hour48Adapter(getActivity(), forecast4Day);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main_hour48,
					container, false);
			hour48Humidity = (TextView) rootView
					.findViewById(R.id.hour48_humidity);
			hour48TempC = (TextView) rootView.findViewById(R.id.hour48_temp);
			hour48Icon = (ImageView) rootView.findViewById(R.id.hour48_icon);
			hour48Date = (TextView) rootView.findViewById(R.id.hour48_date);
			hour48ListView = (MyListView) rootView.findViewById(R.id.listView);
			hour48ListView.setAdapter(hour48Adapter);
			hour48ListView.setOnRefreshListener(new OnRefreshListener() {

				@Override
				public void onRefresh() {
					// 更新数据
					Intent intent = new Intent(getActivity(),
							WeatherService.class);
					intent.putExtra(WeatherService.EXTRA_CITY_NAME, "长沙");
					getActivity().startService(intent);
				}
			});
			return rootView;
		}
	}

	public static class FutureAdapter extends BaseAdapter {

		private ArrayList<ForecastTen> dataSet;
		private LayoutInflater inflater;
		private Context context;

		public FutureAdapter(Context context,
				ArrayList<ForecastTen> forecast10Day) {
			this.context = context;
			dataSet = forecast10Day;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return dataSet.size();
		}

		@Override
		public ForecastTen getItem(int position) {
			return dataSet.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		static class ViewHolder {
			TextView date;
			TextView tempC;
			TextView wind;
			TextView hum;
			ImageView icon;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(
						R.layout.fragment_main_hour48_item, null);
				holder = new ViewHolder();

				holder.date = (TextView) convertView
						.findViewById(R.id.hour48_date);
				holder.tempC = (TextView) convertView
						.findViewById(R.id.hour48_temp);
				holder.hum = (TextView) convertView
						.findViewById(R.id.hour48_humidity);
				holder.icon = (ImageView) convertView
						.findViewById(R.id.hour48_icon);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			ForecastTen forecastTen = forecast10Day.get(position);

			holder.date.setText(forecastTen.getWeekday_short() + "\r\n"
					+ +forecastTen.getMonth() + "月" + forecastTen.getDay());
			holder.tempC.setText(forecastTen.getHighCelsius() + "℃" + "/"
					+ forecastTen.getLowCelsius() + "℃");
			holder.hum.setText(forecastTen.getAvehumidity() + "%");

			// 第三方库: 毕加索
			Picasso.with(context).load(forecastTen.getIconUrl())
					.into(holder.icon);

			return convertView;
		}
	}

	public static class FutureFragment extends Fragment {

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			futureAdapter = new FutureAdapter(getActivity(), forecast10Day);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			View rootView = inflater.inflate(R.layout.fragment_main_hour48,
					container, false);
			hour48Humidity = (TextView) rootView
					.findViewById(R.id.hour48_humidity);
			hour48TempC = (TextView) rootView.findViewById(R.id.hour48_temp);
			hour48Icon = (ImageView) rootView.findViewById(R.id.hour48_icon);
			hour48Date = (TextView) rootView.findViewById(R.id.hour48_date);
			hour48ListView = (MyListView) rootView.findViewById(R.id.listView);
			hour48ListView.setAdapter(futureAdapter);
			hour48ListView.setOnRefreshListener(new OnRefreshListener() {

				@Override
				public void onRefresh() {
					// 更新数据
					Intent intent = new Intent(getActivity(),
							WeatherService.class);
					intent.putExtra(WeatherService.EXTRA_CITY_NAME, "长沙");
					getActivity().startService(intent);
				}
			});
			return rootView;
		}

	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		Toast.makeText(this, locations.get(itemPosition), Toast.LENGTH_SHORT)
				.show();
		return true;
	}

}

通用请求地址:

package com.newer.myweather.API;
/**
 * 通用请求地址
 * @author Engineer-Jsp
 * @date 2014.10.27
 * */
public interface WeatherApi {

	/**
	 * 通过纬度、经度获得城市
	 * http://api.wunderground.com/api/您的key/geolookup/lang
	 * :CN/q/【xx.xxxxxxxx,xx.xxxxxxxx.json】
	 */
	String URL_GEOLOOKUP = "http://api.wunderground.com/api/您的key/geolookup/lang:CN/q/";

	/**
	 * 获得实时天气信息
	 * 
	 * http://api.wunderground.com/api/您的key/conditions/lang:
	 * CN【/q/zmw:00000.1.57679.json】
	 */
	String URL_CONDITIONS = "http://api.wunderground.com/api/您的key/conditions/lang:CN";

	/**
	 * 获得最近四天的天气
	 * 
	 */
	String URL_4DAYS = "http://api.wunderground.com/api/您的key/forecast/lang:CN/q/zmw:00000.1.57679.json";
	/**
	 * 获得最近十天的天气
	 * 
	 */
	String URL_10DAYS = "http://api.wunderground.com/api/您的key/forecast10day/lang:CN/q/zmw:00000.1.57679.json";
}

在主活动界面通知栏左边有Spinner下拉组件和SpinnerAdapter容器,右边有2个ActionBar,分别是地理位置和刷新,设置,点击地理位置可以删除和添加城市,刷新可以拴心天气更新的数据,设置可以设置GPS、通知等,然后下面布局了一GridView,GridLayout

来显示最近四天的天气情况

主界面图展示,今天天气:


地理位置ActionBar操作按钮:


批量删除管理操作:


添加新的城市:


设置按钮操作:


未来48小时天气:


未来10天的天气情况:


左侧按钮城市Spinner下拉组件和SpinnerAdapter容器,主活动还用到了Fragment 俗称素片,用到了划屏事件处理,分别是未来48小时天气活动、主活动、未来10天活动,ViewPager等,由于布局文件xml太多,在讲完APP之后,我会附上源码,到时候大家自行去源码文件里查看和参照xml文件,好了这一篇到此结束,下一篇见!谢谢~!


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。