Create a Service that does a schedule task
Sometimes you need to do a schedule task for a fixed rate (repeatedly), like [check for emails], [check for battery], [update new Facebook status], etc…
The tip here is to use Service and implement a Timer running a TimerTask for an interval.
My sample here is that I like to get Date and Time in every 10 seconds and display a Toast notification to users.
Here how it looks:
So I create my own service called TimeService:
public class TimeService extends Service { // constant public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds // run on another Thread to avoid crash private Handler mHandler = new Handler(); // timer handling private Timer mTimer = null; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { // cancel if already existed if(mTimer != null) { mTimer.cancel(); } else { // recreate new mTimer = new Timer(); } // schedule task mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL); } class TimeDisplayTimerTask extends TimerTask { @Override public void run() { // run on another thread mHandler.post(new Runnable() { @Override public void run() { // display toast Toast.makeText(getApplicationContext(), getDateTime(), Toast.LENGTH_SHORT).show(); } }); } private String getDateTime() { // get date time in custom format SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]"); return sdf.format(new Date()); } }
It’s easy to understand, isn’t it?
Next is to register the TimerService to AndroidManifest for identification.
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".TimeService"/> </application>
Our last step is to give a call for starting our service when activity executes.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService(new Intent(this, TimeService.class)); }
Finally, just run on the phone and see the result.
The implementation is pretty straightforward and simple. You can freely use this way to create some schedule tasks for your applications.
Cheers,
Pete Houston
helpful thank you
Thank you very much. It helped me a lot
hello !
its is not working as a background service . when i close the app i don’t get any notification on the screen.
I can see the notification only when the app starts.otherwise no notification
Add this method to your service, it will run forever unless you stop it from somewhere
@Override
public int onStartCommand(Intent intent, int flags, int startId){
Log.e(TAG, “onStartCommand”);
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
START_STICKY will let your service run even when you leave the app
tôi muốn click tạm dừng thì nó sẽ dừng chạy thời gian thì phải làm thế nào
What do you think for this comments – Do not use services for recurring tasks. A recurring task can start a service, which is another matter entirely.
It is not working in mobile device i tried this to run as back ground service for my application.But it not working can you suggest me
Those getting handler error have imported wrong class
import java.util.logging.Handler;
Change it to
import android.os.Handler;
Thank you for nice coding but runinng is only emulator not On Mobile Device So please suggest Me
private Handler mHandler = new Handler(); (error: Handler is abstract cannot be instantiated)
mHandler.post(new Runnable()) (error: Cannot be recognised as a symbol)
Can anybody solve this error?
See http://stackoverflow.com/a/19873099/3266345
Thank you, your code works perfect
How to stop this service using a stop service button
public void onDestroy()
{
mTimer.cancel();
super.onDestroy();
}
together with…
stopService(new Intent(this, TimeService.class));
Hi, good and complete example.
When are you say “run on another Thread to avoid crash
private Handler mHandler = new Handler();”, what’s mind?
Is necesary the Handler?
Greetings.
Sorry, parser swallow tags put ‘service’ into ‘activity’.
This is help me start on 2.2 emulator.
Thank you!
But yoy code have one mistake.
Put into . On emulator 2.2 this is help me/
Let i want to do some task once a day. In that case the service will keep on running in background, which is of no use. dont you think we should use alarm manager here ?
thank you very much.helps alot