如何安排在android中运行的服务

时间:2013-07-23 11:58:23

标签: android android-service

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);