Android Four Components Learning Service II

Source: Internet
Author: User

The previous section learned how to create a service and start a service with activity. This section is based on a better

This section learns to start the service with StartServer and prints the current time every second in the service

To illustrate:

MyActivity Code:

public class MyActivity extends Activity {private button btn_start;private button btn_end; @Overrideprotected void Oncreat E (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_myservice); Btn_start = (Button) Findviewbyid (r.id.button1);                Btn_end = (Button) Findviewbyid (R.id.button2);               Btn_start.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//Start service Intent Intent = new Intent (myactivity.this, Myservice.class); StartService (Intent);}}); Btn_end.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//Destroy service Intent intent = new Int ENT (Myactivity.this, Myservice.class); StopService (intent);}});}}

MyService's Code:

public class MyService extends Service {@Override//methods that must be implemented public IBinder Onbind (Intent arg0) {//TODO auto-generated Metho D stublog.i ("MyService", "Onbind------------"); return null;} @Override//was created when the call to public void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); LOG.I ("MyService", "OnCreate------------");} @Override @deprecated//onstart method is now replaced by ONSTARTCOMMD, in fact Onstartcommand also called Onstartpublic void OnStart (Intent Intent, int Startid) {//TODO auto-generated Method Stubsuper.onstart (Intent, Startid); LOG.I ("MyService", "OnStart------------");} @Override//Start call public int Onstartcommand (Intent Intent, int flags, int startid) {//TODO auto-generated method stublog.i ("MyService", "Onstartcommand------------"); for (int i=0; i<100; i++) {simpledateformat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String time = Format.format (new Date ()); LOG.I ("MyService", time), try {thread.sleep (+),} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} REturn Super.onstartcommand (Intent, flags, Startid);} @Overridepublic void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); LOG.I ("MyService", "OnDestroy------------");} @Overridepublic boolean onunbind (Intent Intent) {//TODO auto-generated method stublog.i ("MyService", " Onunbind------------"); return Super.onunbind (Intent);}}

Operating effect:

Although the service started, but our interface is the service of the print task card dead. So for this time-consuming task, we have to put it in a thread to prevent the card-dead GUI from displaying

So I made a change to the MyService code:

public class MyService extends Service {    private MyThread thread;    private boolean sto PFlag = false;         @Override//methods that must be implemented     public IBinder onbind (Intent arg0) {        //TODO auto-generated method stub         LOG.I ("MyService", "Onbind------------");        return null;    }          @Override//call to be created     public void OnCreate () {        //TODO auto-generated method stub        super.oncreate ();         //When the service is created, instantiate mythread        thread = new MyThread ( );        log.i ("MyService", "OnCreate------------");    }          @Override      @Deprecated//onstart PartyThe law is now replaced by ONSTARTCOMMD, in fact in Onstartcommand also called the onstart    public void OnStart (Intent Intent, int startid) {         //TODO auto-generated method stub         Super.onstart (Intent, Startid);        log.i ("MyService", "OnStart------------");     }             @Override//start-up will be called      public int Onstartcommand (Intent Intent, int flags, int startid) {        //TODO Auto-gener Ated method stub        log.i ("MyService", "Onstartcommand------------");       after the  //service runs, start thread         if (!stopflag)          {            thread.start ();             thread.setflag (true);       &Nbsp;    }        return super.onstartcommand (Intent, flags, Startid);     }         @Override     public void OnDestroy () {         //TODO auto-generated method stub         Super.ondestroy ();        //Service when destroying, stop thread tasks          Thread.setflag (False);        log.i ("MyService", "OnDestroy------------");     }         @Override     public boolean onunbind (Intent Intent ) {        //TODO auto-generated method stub        log.i ( "MyService", "Onunbind------------");        return super.onunbind (Intent);     }        class MyThread extends thread    {                //settings flag         public void Setflag (Boolean flag)         {       & nbsp;    stopflag = flag;        }         @Override         public void Run () {           & Nbsp;super.run ();            while (stopflag)              {                // Set the time output mode                 simpledateformat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");                String  time = Format.format (new Date ());       &NBsp;                        //display time                 log.i ("MyService";                                  try {                    //Delay One second                      thread.sleep (;  )              } catch ( Interruptedexception e) {                    //TODO auto-generated catch block                & nbsp;   e.printstacktrace ();                }            }        }    }}

The results are as follows:

When I click on the button that starts the service

You can see that when you click the Start Service button, create first, then Onstartcommand (Onstart)

When I then press Start service:

You can see that when the service starts again and starts the service again, it will only call the Onstartcommand function's

Then destroy the service:

You can see that the service is destroyed and our thread tasks are stopped.



Ok. This is where you start the service today with StartServer.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Four Components Learning Service II

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: info-contact@alibabacloud.com 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.