2

我的应用程序中有一个服务,它发出一些 API 请求并使用响应中提供的数据,有没有办法安排服务每小时运行一次谢谢

4

2 回答 2

6

我最后就是这样做的:

Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, ProximityAlertService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Log.d("Main",String.valueOf( cal.getTimeInMillis()));
//make the alarm goes off every 10 sec (not exact help to save battery life)
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 10000, pintent);
于 2013-07-25T10:05:56.800 回答
1

例如:

    AlarmManager service = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, LocationPoller.class);

    Bundle bundle = new Bundle();
    LocationPollerParameter parameter = new LocationPollerParameter(bundle);
    parameter.setIntentToBroadcastOnCompletion(new Intent(context, MyStartServiceReceiver.class));
    // try GPS and fall back to NETWORK_PROVIDER
    parameter.setProviders(new String[] {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER});
    parameter.setTimeout(60000);
    i.putExtras(bundle);


    PendingIntent pending = PendingIntent.getBroadcast(context, 54321, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal = Calendar.getInstance();
    // Start 30 seconds after boot completed
    service.cancel(pending);
    cal.add(Calendar.SECOND, 30);
    //
    // Fetch every 30 seconds
    // InexactRepeating allows Android to optimize the energy consumption
    service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), REPEAT_TIME, pending);
于 2013-07-23T12:09:16.230 回答