Background update (IV)

Source: Internet
Author: User

Implementation principle:

Create a service class, create a Broadcastreceiver class, and use the OnReceive () method of this class;;;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= "" + Weathercode + ". html"; Httputil.sendhttprequest (Address,NewHttpcallbacklistener () {@Override Public voidonfinish (String response) {utility.handleweatherresponse (autoupdateservice. This, response); } @Override Public voidOnError (Exception e) {e.printstacktrace ();    }        }); }}

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);    }};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 (; Citynametext=(TextView) Findviewbyid (; Publishtext=(TextView) Findviewbyid (; Weatherdesptext=(TextView) Findviewbyid (R.ID.WEATHER_DESP); Temp1text=(TextView) Findviewbyid (R.ID.TEMP1); Temp2text=(TextView) Findviewbyid (R.ID.TEMP2); Currentdatetext=(TextView) Findviewbyid (; Switchcity=(Button) Findviewbyid (; Refreshweather=(Button) Findviewbyid (; 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 ()) { Intent=NewIntent ( This, Chooseareaactivity.class); Intent.putextra ("From_weather_activity",true);            StartActivity (Intent);            Finish ();  Break; ("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://" + Countycode + ". Xml"; Queryfromserver (Address,"Countycode"); }    /*** Check the weather for weather codes. */    Private voidqueryweatherinfo (String weathercode) {string address= "" + 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.