17

I was searching over the internet for last 2 days but I couldn't find any tutorial helpful. I have created a service and I am sending a notification in status bar when the service starts. I want that service to stop after showing the notification and start it again after 5 minutes. Please let me know if it is possible and provide me some helpful tutorials if you have any. I heard of TimerTask and AlarmManager and I tried to use them as well but I wasn't able to get the desired result.

EDIT: I need the service to be started every 5 minutes even if my application is not running.

Kashif Umair Liaqat
  • 1,064
  • 1
  • 18
  • 27

3 Answers3

25

You do not want to use a TimerTask since this depends on your application running continuously. An AlarmManager implementation makes it safe for your application to be killed between executions.

Stating that you tried to use AlarmManager but did not get the desired result is not a helpful statement, in that it tells no one how to help you to get it right. It would be much more useful to express what happened.

http://web.archive.org/web/20170713001201/http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/ contains what appears to be a useful tutorial on AlarmManager. Here are the salient points:

1) Your alarm will cause an Intent to fire when it expires. It's up to you to decide what kind of Intent and how it should be implemented. The link I provided has a complete example based on a BroadcastReceiver.

2) You can install your alarm with an example such as:

public void setOnetimeTimer(Context context) {
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.TRUE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 5), pi);
}
Ryan M
  • 18,333
  • 31
  • 67
  • 74
mah
  • 39,056
  • 9
  • 76
  • 93
  • 2
    Nice approach, really. You should use AlarmManager this way;`Calendar wakeUpTime = Calendar.getInstance(); wakeUpTime.add(Calendar.SECOND, seconds); AlarmManager aMgr = (AlarmManager) getSystemService(ALARM_SERVICE); aMgr.set(AlarmManager.RTC_WAKEUP, wakeUpTime.getTimeInMillis(), pendingIntent);` – Alpay Dec 11 '12 at 12:53
  • 1
    I used AlarmManager for same purpose. I set 2 minutes in AlarmManager. But AlarmManager is fire randomly. I think it is not best way to call every 2 minutes using AlarmManager. – kels Mar 31 '14 at 11:30
  • http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/ is not working – Ravi Yadav Oct 25 '19 at 06:37
  • @mah can i send the location every 5 sec in the background even when the app goes to background? in my app stop sending location in background after 10 min and I'm using Timer. – Farhana Naaz Ansari Jul 05 '21 at 13:30
  • this is nice but the user said he has to run it every five minutes so maybe using AlarmManager.setRepeating(...) be better. adding the documentation here: https://developer.android.com/reference/android/app/AlarmManager#setRepeating(int,%20long,%20long,%20android.app.PendingIntent) – shaked428 Sep 22 '22 at 07:56
14

Below I have provided three files, MainActivity.java for start service, Second file MyService.java providing service for 5 Minute and Third is manifest file.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, MyService.class)); //start service which is MyService.java
    }
}

MyService.java

 public class MyService extends Service {

    public static final int notify = 300000;  //interval between two services(Here Service run every 5 Minute)
    private Handler mHandler = new Handler();   //run on another Thread to avoid crash
    private Timer mTimer = null;    //timer handling

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        if (mTimer != null) // Cancel if already existed
            mTimer.cancel();
        else
            mTimer = new Timer();   //recreate new
        mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);   //Schedule task
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();    //For Cancel Timer
        Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
    }

    //class TimeDisplay for handling task
    class TimeDisplay extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // display toast
                    Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

AndroidManifest.xml

  <service android:name=".MyService" android:enabled="true" android:exported="true"></service>
Sagar Naliyapara
  • 3,971
  • 5
  • 41
  • 61
Khyati Vara
  • 1,042
  • 13
  • 22
-4

Create a Timer object and give it a TimerTask that performs the code you'd like to perform.

Timer timer = new Timer ();
TimerTask hourlyTask = new TimerTask () {
    @Override
    public void run () {
        // your code here...
    }
};

// schedule the task to run starting now and then every hour...
timer.schedule (hourlyTask, 0l, 1000*60*60);   // 1000*10*60 every 10 minut

The advantage of using a Timer object is that it can handle multiple TimerTask objects, each with their own timing, delay, etc. You can also start and stop the timers as long as you hold on to the Timer object by declaring it as a class variable or something.

Nirav Ranpara
  • 13,753
  • 3
  • 39
  • 54
  • 10
    Downvoted; a Timer is absolutely a poor solution to this because Android can terminate the application and if you are using a Timer or TimerTask, it cannot be dealt with. It's not "working code", it's "working under ideal conditions only" code. – mah Dec 11 '12 at 12:43
  • 2
    Agree with @mah, I also saw some comments against timer on some of the questions. BTW I appreciate Nirav Ranpara for participation. Can you provide a solution with AlarmManager. – Kashif Umair Liaqat Dec 11 '12 at 12:47
  • 1
    I am really sorry to mention that I want this service to be started every 5 minutes even if my application is not running. I have edited the question as well. – Kashif Umair Liaqat Dec 11 '12 at 12:49
  • @mah : ok. can you please say me how to do ? – Nirav Ranpara Dec 11 '12 at 12:50
  • @NiravRanpara please see my answer, and the tutorial it links to for one source of more details. Note that googling "alarmmanager tutorial" will locate several additional tutorials, I just chose the first one listed. – mah Dec 11 '12 at 12:52