Advertisement
Guest User

Untitled

a guest
Oct 21st, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. package com.example.nihal.myapplication;
  2.  
  3. import android.app.Service;
  4. import android.content.Intent;
  5. import android.os.Handler;
  6. import android.os.IBinder;
  7. import android.widget.Toast;
  8.  
  9. import java.text.SimpleDateFormat;
  10. import java.util.Date;
  11. import java.util.Timer;
  12. import java.util.TimerTask;
  13.  
  14. /**
  15. * Created by Boiijek on 21/10/2017.
  16. */
  17.  
  18. public class TimeService extends Service {
  19. // constant
  20. public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds
  21.  
  22. // run on another Thread to avoid crash
  23. private Handler mHandler = new Handler();
  24. // timer handling
  25. private Timer mTimer = null;
  26.  
  27. @Override
  28. public IBinder onBind(Intent intent) {
  29. return null;
  30. }
  31.  
  32. @Override
  33. public void onCreate() {
  34. // cancel if already existed
  35. if(mTimer != null) {
  36. mTimer.cancel();
  37. } else {
  38. // recreate new
  39. mTimer = new Timer();
  40. }
  41. // schedule task
  42. mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
  43. }
  44.  
  45. class TimeDisplayTimerTask extends TimerTask {
  46.  
  47. @Override
  48. public void run() {
  49. // run on another thread
  50. mHandler.post(new Runnable() {
  51.  
  52. @Override
  53. public void run() {
  54. // display toast
  55. Toast.makeText(getApplicationContext(), getDateTime(),
  56. Toast.LENGTH_SHORT).show();
  57. }
  58.  
  59. });
  60. }
  61.  
  62. private String getDateTime() {
  63. // get date time in custom format
  64. SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
  65. return sdf.format(new Date());
  66. }
  67.  
  68. }
  69.  
  70.  
  71. @Override
  72. public void onDestroy()
  73. {
  74. mTimer.cancel();
  75. super.onDestroy();
  76. Toast.makeText(this, "TimeService has stopped!",Toast.LENGTH_LONG).show();
  77.  
  78. }
  79.  
  80.  
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement