Service and AlarmManager

大兔子大兔子 提交于 2019-12-23 06:14:37

问题


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--------------------------
     }

    }


来源:https://stackoverflow.com/questions/19316015/service-and-alarmmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!