如何安排在android中的特定时间服务

时间:2015-07-15 16:28:09

标签: android android-service alarmmanager android-pendingintent

我正在制作演示安卓项目,其中我想在8:00时钟每天安排服务。我从我的启动器活动中调用此方法。每当我启动应用程序时,调用下面的方法,然后同时启动服务并显示通知。我只希望它应该以这样的方式安排,它应该在8:00执行,而不是每次我打开应用程序。

public static void scheduleVerseNotificationService(Context mContext) {
    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(mContext, Notification.class);
    PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, intent, 0);

    // Set the alarm to start at approximately 08:00 morning.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 8);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

}

由于

3 个答案:

答案 0 :(得分:2)

似乎您为已经通过的时间安排计时器,因此一旦您请求alarmManager.setInexactRepeating

就会调用它

以下是修复问题的代码:

public static void scheduleVerseNotificationService(Context mContext) {
    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(mContext, Notification.class);
    PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, intent, 0);

    // reset previous pending intent
    alarmManager.cancel(pendingIntent);

    // Set the alarm to start at approximately 08:00 morning.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 8);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    // if the scheduler date is passed, move scheduler time to tomorrow
    if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
        calendar.add(Calendar.DAY_OF_YEAR, 1);
    }

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pendingIntent);
}

答案 1 :(得分:0)

我在理解你的问题时遇到了一些麻烦:

 I only want it should schedule in such a way it should execute at 8:00 instead of everytime I open app.

我理解为"我只想在8:00执行一个Activity,而不是在我开始那个Activity" 所以,建议是:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent YOUR_INTENT = getIntent();
if (YOUR_INTENT!= null) {
 if(YOUR_INTENT.getStringExtra("YOUR_PACKAGE.A_VAR_NAME") != null){
  if (YOUR_INTENT.getStringExtra("YOUR_PACKAGE.A_VAR_NAME").equals("A VALUE")) {
   DO_THE_CODE_YOU_WANT();
  }
}

然后,根据您的意图,您添加一个值:intent.putExtra("YOUR_PACKAGE.A_VAR_NAME", "A VALUE");

答案 2 :(得分:0)

尝试将此行用于pendingIntent

pendingIntent= PendingIntent.getBroadcast(mContext, 0, intent, 0);