Frage

I am using AlarmManager of Android and scheduling a repeating alarm using elapsed_time_wakeup for every minute. This alarm fires of a service.

Service does its work (pinging the server(Facebook server in my case) to get data). Next I call onDestroy() of the service. So every minute Service starts -> Does work -> onDestroy()

Is the best way to do this in android?

War es hilfreich?

Lösung

Do you really need new service every minute? I think you want to start single service. That service does each minute check on server and reports success or error somehow? You want simple always running service with periodic action, not periodic service starting. In this case, starting new service would consume maybe more resources than check itself.

Just make sure service stays running. That might be case until you call stopSelf() from it and starting activity does not stop it also. You may want to run it as

private ping() {
  // periodic action here.
  scheduleNext();
}

private scheduleNext() {
  mHandler.postDelayed(new Runnable() {
    public void run() { ping(); }
  }, 60000);
}

int onStartCommand(Intent intent, int x, int y) {
  mHandler = new android.os.Handler();
  ping();
  return STICKY;
}

You might want periodic check only on Wifi connection or connection present. And maybe to stop checking when you already know about problem and are solving it. You may want to use startForeground() from Service to start some activity to control it and display results.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top