這個案例只是為了關聯各個知識點,在實際開發中還有待最佳化
項目結構分析:
Weather實體類:用來存放我們的天氣實體
WeatherManager: 用來操作Weather
MainActivity:主acaitivy
CityWeatherService:定時輪詢來更新前台的資訊
原理比較簡單直接貼出代碼:
Weather:
package com.example.weatherdemo;public class Weather{private String cityName;private String cityData;private String cityWeath;private String cityWinder;private String cityImg;public Weather(){}public Weather(String cityName,String cityData,String cityWeath,String cityWinder,String cityImg){this.cityName = cityName;this.cityData = cityData;this.cityWeath = cityWeath;this.cityWinder = cityWinder;this.cityImg = cityImg;}public String getCityName(){return cityName;}public void setCityName(String cityName){this.cityName = cityName;}public String getCityData(){return cityData;}public void setCityData(String cityData){this.cityData = cityData;}public String getCityWeath(){return cityWeath;}public void setCityWeath(String cityWeath){this.cityWeath = cityWeath;}public String getCityWinder(){return cityWinder;}public void setCityWinder(String cityWinder){this.cityWinder = cityWinder;}public String getCityImg(){return cityImg;}public void setCityImg(String cityImg){this.cityImg = cityImg;}}
WeatherManager:
package com.example.weatherdemo;import org.json.JSONException;import org.json.JSONObject;public class WeatherManager{Weather weather;public void setWeather(String jsonString){try{JSONObject jsonObject = new JSONObject( jsonString );JSONObject object = jsonObject.getJSONObject( "weatherinfo" );String cityName = object.getString( "city" );String cityData = object.getString( "date_y" ); String cityWeath = object.getString( "weather1" ); String cityWinder = object.getString( "wind1" ); String cityImg = object.getString( "img1" ); weather = new Weather( cityName, cityData, cityWeath, cityWinder, cityImg );}catch (JSONException e){// TODO Auto-generated catch blocke.printStackTrace();}}public Weather getWeather(){return weather;}}
CityWeatherService:
package com.example.weatherdemo;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.Timer;import java.util.TimerTask;import android.app.Service;import android.content.BroadcastReceiver;import android.content.Intent;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.util.Log;public class CityWeatherService extends Service{private static final int UPDATAWEATHER = 0X10;private final int GOTOBROADCAST = 0X20;public static final String BROADCASTACTION = "com.jone.broad";Timer timer;@Overridepublic IBinder onBind(Intent arg0){// TODO Auto-generated method stubreturn null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId){// updateWeather();timer = new Timer();timer.schedule( new TimerTask(){@Overridepublic void run(){// 定時更新String jsonString = getWeather();// 發送廣播Intent intent = new Intent();intent.setAction( BROADCASTACTION );intent.putExtra( "jsonstr", jsonString );sendBroadcast( intent );// Message msg = handler.obtainMessage();// msg.what = UPDATAWEATHER;// handler.sendMessage( msg );}}, 0, 20 * 1000 );return super.onStartCommand( intent, flags, startId );}private String getWeather(){String srsString = "";try{srsString = getJsonStringGet( "http://m.weather.com.cn/data/101250101.html" );}catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();Log.i( "tag",e.getMessage() );}return srsString;}public String getJsonStringGet(String uri) throws Exception{String result = null;URL url = new URL( uri );HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout( 6 * 1000 );// 設定連線逾時Log.i( "msg", conn.getResponseCode() + "???????" );if (conn.getResponseCode() == 200){Log.i( "msg", "成功" );InputStream is = conn.getInputStream();// 得到網路返回的輸入資料流result = readData( is, "UTF-8" );}else{Log.i( "msg", "失敗" );result = "";}conn.disconnect();return result;}private String readData(InputStream inSream, String charsetName) throws Exception{ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = -1;while ((len = inSream.read( buffer )) != -1){outStream.write( buffer, 0, len );}byte[] data = outStream.toByteArray();outStream.close();inSream.close();return new String( data, charsetName );}@Overridepublic void onDestroy(){// TODO Auto-generated method stubsuper.onDestroy();if(timer != null){timer.cancel();}}}
MainActivity:
package com.example.weatherdemo;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.view.Menu;import android.widget.TextView;public class MainActivity extends Activity{BroadcastMain broadcastMain ;Weather weather;public static WeatherManager manager;TextView cityTextView;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate( savedInstanceState );setContentView( R.layout.activity_main );cityTextView = (TextView) findViewById( R.id. city);manager = new WeatherManager();Intent intent = new Intent(); intent.setClass(this, CityWeatherService.class); startService(intent);broadcastMain = new BroadcastMain();IntentFilter filter = new IntentFilter();filter.addAction( CityWeatherService.BROADCASTACTION );registerReceiver( broadcastMain, filter );}@Overridepublic boolean onCreateOptionsMenu(Menu menu){// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate( R.menu.main, menu );return true;}public class BroadcastMain extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent){//String jsonString = intent.getExtras().getString( "jsonstr" );//manager.setWeather( jsonString );Message msg = handler.obtainMessage();msg.what = 01;handler.sendMessage( msg );}}Handler handler = new Handler(){public void handleMessage(android.os.Message msg){switch (msg.what){case 01:weather = manager.getWeather();cityTextView.setText( weather.getCityName() );break;default:break;}};};@Overrideprotected void onDestroy(){Intent intent = new Intent(); intent.setClass(this, CityWeatherService.class); stopService(intent);super.onDestroy();}}
主要的功能實現在service中,開啟一個定時器,去擷取服務端的資訊,通過廣播來即時我們的activity中相關的組件