here is what am trying to accomplish and badly failing at it.
I need to:
-start a service
-do some tasks
-set AlarmManager to start the service again after a set period of time
-stop the service
the problem I'm having is that the service is being re-started almost immediately it is being stopped. All I want is that the service should start after the alarm goes off..
Here is the code:-
Intent intent = new Intent(ThisService.this,
ThisService.class);
PendingIntent pendingIntent = PendingIntent.getService(ThisService.this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
getUpdateTime(), getUpdateTime(), pendingIntent);
stopSelf();
what you are missing is the broadcast reciever
The flow should be
- Start Service.
- Create a BroadCast Reciever
- Perform Task in service
- Set Alarm to Trigger BroadCast Recievr( on Reception of bradcast reciever start Service again.)
- Call StopSelf it will stop your service which can be restarted from broadcast recievr
please refer to http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
//-----Set the alarm to trigger the broadcast reciver-----------------------------
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",
Toast.LENGTH_LONG).show();
//---------------Call StopSelf here--------------------
//----------------------------------------------------------------------------------
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//-----------write code to start the service--------------------------
}
}