Service and AlarmManager

2019-06-14 17:42发布

问题:

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();

回答1:

what you are missing is the broadcast reciever

The flow should be

  1. Start Service.
  2. Create a BroadCast Reciever
  3. Perform Task in service
  4. Set Alarm to Trigger BroadCast Recievr( on Reception of bradcast reciever start Service again.)
  5. 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--------------------------
     }

    }