1

早上 8 点开始我的服务。我不知道如何在特定时间停止服务。

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyService.class);
PendingIntent pi = PendingIntent.getService(this,
(int) System.currentTimeMillis(), intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pi);

我希望 Myservice 每天早上 8 点开始,下午 6 点停止。

请帮我。谢谢。

4

3 回答 3

0

您可以在 myService.class 中使用 AlarmManager, .cancel(PendingIntent intent),检查是否是下午 6 点,如果存在则取消警报。

检查 API: 警报管理器 API

于 2012-10-02T09:42:41.233 回答
0

This might be an old question but I came across this issue myself today and figured a way to do it: You can use a new service which stops your service, and start that service in the desired time on a daily basis using alarm manager, like this:

Define the service which will stop your service:

package com.youractivity;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;


public class MyServiceTerminator extends Service {

  @Override
public int onStartCommand(Intent intent, int flags, int startId) {
      return Service.START_NOT_STICKY;
  }


public void onCreate()
  {
     Intent service = new Intent(this, MyService.class);
    stopService(service);   //stop MyService
    stopSelf();     //stop MyServiceTerminator so that it doesn't keep running uselessly
  }

  @Override
  public IBinder onBind(Intent intent) {
  //TODO for communication return IBinder implementation
    return null;
  }
} 

add the following code after the one you posted, and run the method inside your activity:

private void stopRecurringAlarm(Context context) {
    Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getTimeZone("GMT+3"));
    updateTime.set(Calendar.HOUR_OF_DAY, 18);
    updateTime.set(Calendar.MINUTE, 0);
    Intent intent = new Intent(this, MyServiceTerminator.class);
    PendingIntent pintent = PendingIntent.getService(context, 1, intent,    PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarms.setRepeating(AlarmManager.RTC_WAKEUP,updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pintent);
}

this way the service will be scheduled to start as you posted above, and scheduled to stop at 6 as shown in the code I posted.

于 2013-04-07T15:42:53.953 回答
0

您可以使用 AlarmManager 进行调度和取消方法来停止。

alarmMgr.cancel(alarmIntent); 

您可以在这里找到所有必要的信息 https://developer.android.com/training/scheduling/alarms.html

于 2014-07-19T22:49:27.560 回答