Android-Timer Service-timer

Source: Internet
Author: User

Note: In a project, sometimes there may be some scheduled tasks, at which point a timer is typically written in a service.

Cases:

Service class:

Import Java.util.Timer;

Import Java.util.TimerTask;

Import Android.app.Service;

Import android.content.Intent;

Import Android.os.IBinder;

public class Timerservice extends Service {

Timer timer; Timer

TimerTask task;//timed execution of tasks

@Override

Public IBinder Onbind (Intent Intent) {

return null;

}

@Override

public void OnCreate () {

Timer = new timer ();

task = new TimerTask () {

@Override

public void Run () {

try {

Thread.Sleep (1000);

System.out.println ("performed a timed task");

} catch (Interruptedexception e) {

E.printstacktrace ();

}

}

};

Parameter description: 1, Task 2, delay the specified time after the start of execution 3, repeat the task at the specified frequency

Timer.scheduleatfixedrate (Task, 1000, 1000);

Super.oncreate ();

}

@Override

public void OnDestroy () {

SYSTEM.OUT.PRINTLN ("Stop timed Task");

Timer.cancel ();

Task.cancel ();

Super.ondestroy ();

}

}

Use:

Import android.app.Activity;

Import android.content.Intent;

Import Android.os.Bundle;

Import Android.view.View;

Import Android.view.View.OnClickListener;

Import Android.widget.Button;

public class Mainactivity extends Activity {

Button Btn_start;

Button Btn_stop;

@Override

protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_main);

Final Intent Intent =new Intent (Mainactivity.this, Timerservice.class);

Btn_start = (Button) Findviewbyid (R.id.btn_start);

Btn_stop = (Button) Findviewbyid (r.id.btn_stop);

Btn_start.setonclicklistener (New Onclicklistener () {

@Override

public void OnClick (View v) {

StartService (Intent);

}

});

Btn_stop.setonclicklistener (New Onclicklistener () {

@Override

public void OnClick (View v) {

StopService (Intent);

}

});

}

}

Android-Timer Service-timer

Related Article

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.