Skip to main content

Timer task using service

Timer task using service in android

// To run a  task for a specific time in background using service in android

// Example program for to display a toast message for every one minute(exactly 1 minute)

//Use service in android, then only it runs in background.


public class MyService extends Service
{
            private static Timer timer = new Timer();
          
           @Override
            public IBinder onBind(Intent intent)
           {
                    // TODO Auto-generated method stub
                    return null;
             }

            @Override
             public void onCreate()
           {
                      Log.d("Service Creating", "onCreate method running");

                     // Creating service
                      super.onCreate();
                      ctx = this;

                     // Starting service
                      startService();
             }

            private void startService()
            {        
                     Log.i("Service Started","com"); 
                     timer.scheduleAtFixedRate(new mainTask(), 0, 60000); //60000=1 min &1000=1 sec
             }

            private class mainTask extends TimerTask
            {
                         public void run()
                         {
                                  Toast.makeText(this, "Now 1 minute finished",Toast.LENGTH_LONG).show();
                          }
             }
}


// Use this in manifest xml file

<service android:enabled="true" android:name=".MyService" />



http://sourcecodeandroid.blogspot.in by T.s.Mathavan
                           

Comments

Popular posts from this blog

Email pattern validation

//Email pattern validation In this example the email is validated and returns True or False package com.***; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.util.Log; public class EmailValidator {            private Pattern pattern;            private Matcher matcher;            private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";                public Boolean validate(String email)            {                          pattern = Pattern.compile(EMAIL_PATTERN);                          matcher = pattern.matcher(email);         ...

Current date and Time in different formats Using Calendar

Current date and time in different formats using Calendar function                     Calendar c=Calendar.getInstance();                       //for current date             SimpleDateFormat sdf1=new SimpleDateFormat("dd-MM-yyyy");             String date1 = sdf1.format(c.getTime());             //value of date1 is 27-04-2012             SimpleDateFormat sdf_db=new SimpleDateFormat("yyyy-MM-dd");             String date_db=sdf_db.format(c.getTime());             //value of date_db is 2012-04-27  ...