Implementation principle:
Create a service class, create a Broadcastreceiver class, and use the OnReceive () method of this class
Autoupdateservice.java
ImportAndroid.app.AlarmManager;Importandroid.app.PendingIntent;ImportAndroid.app.Service;Importandroid.content.Intent;Importandroid.content.SharedPreferences;ImportAndroid.os.IBinder;ImportAndroid.os.SystemClock;ImportAndroid.preference.PreferenceManager; Public classAutoupdateserviceextendsService {@Override Publicibinder onbind (Intent Intent) {return NULL; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) { NewThread (NewRunnable () {@Override Public voidrun () {updateweather (); }}). Start (); Alarmmanager Manager=(Alarmmanager) Getsystemservice (Alarm_service); intAnhour = 8 * 60 * 60 * 1000;//This is the 8-hour millisecond number. LongTriggerattime = Systemclock.elapsedrealtime () +Anhour; Intent I=NewIntent ( This, Autoupdatereceiver.class); Pendingintent Pi= Pendingintent.getbroadcast ( This, 0, I, 0); Manager.set (Alarmmanager.elapsed_realtime_wakeup, Triggerattime, pi); return Super. Onstartcommand (Intent, flags, Startid); } /*** Update weather information. */ Private voidUpdateweather () {sharedpreferences prefs=Preferencemanager. Getdefaultsharedpreferences ( This); String Weathercode= Prefs.getstring ("Weather_code", "" "); String Address= "http://www.weather.com.cn/data/cityinfo/" + Weathercode + ". html"; Httputil.sendhttprequest (Address,NewHttpcallbacklistener () {@Override Public voidonfinish (String response) {utility.handleweatherresponse (autoupdateservice. This, response); } @Override Public voidOnError (Exception e) {e.printstacktrace (); } }); }}
Autoupdatereceiver.java
Import Android.content.BroadcastReceiver; Import Android.content.Context; Import android.content.Intent; Public class extends broadcastreceiver { @Override publicvoid onreceive (context context, Intent Intent) { new Intent (context, Autoupdateservice. Class); Context.startservice (i); }}
Weatheractivity.java
Importandroid.app.Activity;Importandroid.content.Intent;Importandroid.content.SharedPreferences;ImportAndroid.os.Bundle;ImportAndroid.preference.PreferenceManager;Importandroid.text.TextUtils;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.view.Window;ImportAndroid.widget.Button;Importandroid.widget.LinearLayout;ImportAndroid.widget.TextView; Public classWeatheractivityextendsActivityImplementsOnclicklistener {PrivateLinearLayout weatherinfolayout; /*** Used to show the city name the 14th chapter entered the actual combat, the development of cool European weather 533*/ PrivateTextView Citynametext; /*** Used to display the release time*/ PrivateTextView Publishtext; /*** Used to display weather description information*/ PrivateTextView Weatherdesptext; /*** used to show temperature 1*/ PrivateTextView Temp1text; /*** used to show temperature 2*/ PrivateTextView Temp2text; /*** Used to display the current date*/ PrivateTextView Currentdatetext; /*** Toggle City button*/ PrivateButton switchcity; /*** Update Weather button*/ PrivateButton Refreshweather; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.weather_layout); //Initialize each controlWeatherinfolayout =(LinearLayout) Findviewbyid (r.id.weather_info_layout); Citynametext=(TextView) Findviewbyid (r.id.city_name); Publishtext=(TextView) Findviewbyid (R.id.publish_text); Weatherdesptext=(TextView) Findviewbyid (R.ID.WEATHER_DESP); Temp1text=(TextView) Findviewbyid (R.ID.TEMP1); Temp2text=(TextView) Findviewbyid (R.ID.TEMP2); Currentdatetext=(TextView) Findviewbyid (r.id.current_date); Switchcity=(Button) Findviewbyid (r.id.switch_city); Refreshweather=(Button) Findviewbyid (R.id.refresh_weather); String Countycode= Getintent (). Getstringextra ("County_code"); if(!Textutils.isempty (Countycode)) { //Check the weather if you have a county code.Publishtext.settext ("In sync ..."); Weatherinfolayout.setvisibility (view.invisible); Citynametext.setvisibility (view.invisible); Queryweathercode (Countycode); } Else { //Direct display of local weather without county codeShowweather (); } switchcity.setonclicklistener ( This); Refreshweather.setonclicklistener ( This); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { Caser.id.switch_city:intent Intent=NewIntent ( This, Chooseareaactivity.class); Intent.putextra ("From_weather_activity",true); StartActivity (Intent); Finish (); Break; CaseR.id.refresh_weather:publishtext.settext ("In sync ..."); Sharedpreferences prefs=Preferencemanager. Getdefaultsharedpreferences ( This); String Weathercode= Prefs.getstring ("Weather_code", "" "); if(!Textutils.isempty (Weathercode)) {Queryweatherinfo (Weathercode); } Break; default: Break; } } /*** Check the corresponding weather code for the county code. */ Private voidQueryweathercode (String countycode) {string address= "Http://www.weather.com.cn/data/list3/city" + Countycode + ". Xml"; Queryfromserver (Address,"Countycode"); } /*** Check the weather for weather codes. */ Private voidqueryweatherinfo (String weathercode) {string address= "http://www.weather.com.cn/data/cityinfo/" + Weathercode + ". html"; Queryfromserver (Address,"Weathercode"); } /*** According to the incoming address and type to the server to query weather code or weather information. */ Private voidQueryfromserver (FinalString address,FinalString type) {httputil.sendhttprequest (address,NewHttpcallbacklistener () {@Override Public voidOnFinish (FinalString Response) { if("Countycode". Equals (Type) { if(!Textutils.isempty (response)) { //parse out the weather code from the data returned from the serverstring[] Array = response.split ("\\|"); if(Array! =NULL&& Array.Length = = 2) {String Weathercode= Array[1]; Queryweatherinfo (Weathercode); } } } Else if("Weathercode". Equals (Type) { //processing The weather information returned by the serverUtility.handleweatherresponse (weatheractivity. This, response); Runonuithread (NewRunnable () {@Override Public voidrun () {showweather (); } }); }} @Override Public voidOnError (Exception e) {runonuithread (NewRunnable () {@Override Public voidrun () {Publishtext.settext ("Synchronization Failed"); } }); } }); } /*** Read the stored weather information from the Sharedpreferences file and display it to the interface. */ Private voidShowweather () {sharedpreferences prefs=Preferencemanager. Getdefaultsharedpreferences ( This); Citynametext.settext (Prefs.getstring ("City_name", "" ")); Temp1text.settext (Prefs.getstring ("Temp1", "" ")); Temp2text.settext (Prefs.getstring ("Temp2", "" ")); Weatherdesptext.settext (Prefs.getstring ("Weather_desp", "" ")); Publishtext.settext ("Today" + prefs.getstring ("Publish_time", "") + "release"); Currentdatetext.settext (Prefs.getstring ("Current_date", "" ")); Weatherinfolayout.setvisibility (view.visible); Citynametext.setvisibility (view.visible); Intent Intent=NewIntent ( This, Autoupdateservice.class); StartService (Intent); }}
Background update (IV)