Android:在选定的时间启动服务

时间:2014-10-23 14:13:16

标签: java android android-service alarmmanager android-calendar

我有一个BroadcastReceiver启动服务。在这项服务中我有一个AlarmManager我想在每天的某个特定时间开始另一项服务。

当我打开应用程序时,BroadcastReceiver启动,但如果我在设定的时间启动BroadCastReceiver,则AlarmManager仅启动其服务。

如何让它不断地将当前时间与设定时间进行比较,以便在时机成熟时自动运行?

在MainActivity.java中

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent();   
    intent.setAction("com.example.BroadcastPro.MyBroadcastReceiver");   
    sendBroadcast(intent);  
}

在myBroadcastReceiver.java中

public class MyBroadcastReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Intent  i=new Intent(context,SetPeriodicService.class);    
        context.startService(i);
    }
}

在SetPeriodicService.java

public int onStartCommand(Intent intent, int flags, int startId)    
{
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 12);
    calendar.set(Calendar.MINUTE, 30);  

    Intent i=new Intent(this,MyService.class);  
    PendingIntent alarmIntent = PendingIntent.getService(this, 0, i, 0);
    AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmManager.INTERVAL_DAY, alarmIntent);

    return super.onStartCommand(intent, flags, startId);    
}

1 个答案:

答案 0 :(得分:0)

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmManager.INTERVAL_DAY, alarmIntent);的SetPeriodicService.java中 您需要更改为alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmMgr.INTERVAL_DAY, alarmIntent);