Android Timer to schedule a task

In this Android tip, I am going to show you how to use Timer and TimerTask to schedule an action or task to be performed later in the future. Typically, the Timer class is used with the TimerTask class. The task to performed is written in the run() method of the TimerTask class. Then this task can be scheduled to run at a specific time in the future using the schedule() or scheduleAtFixedRate() method. If you want to do the task only once, use schedule() method. It allows you to do the task after a time delay. Otherwise, you use the scheduleAtFixedRate() method to do the task repeatedly.
In the example code below, The Timer is used to turn the screen off 5 seconds later when the application starts. You can use the PowerManager and WakeLock to turn the screen on and off with the acquire() and release() method. You should note that FULL_WAKE_LOCK is deprecated in API level 17. However, it is still useful in this example code.
To use WakeLock you must request the android.permission.WAKE_LOCK permission in an <uses-permission> element of the application's manifest.

package com.example.andtimer;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;

public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
// Get PowerManager instance
     PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
     // Create a WakeLock
     final PowerManager.WakeLock wakeLock= pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
     // Make sure the screen is on
      // Create Timer object
     Timer timer = new Timer();
     // Create Task object
     TimerTask task = new TimerTask() {
        public void run() {
     // Turn the screen of in 50 seconds later
     timer.schedule(task, 50000);
     // Repeat the task
     //timer.scheduleAtFixedRate(task, 50000, 2000);


Posted by: Dara | post date: 12-01-2014 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.