Search code examples
androidclojuregen-class

Creating an Android Service in Clojure


I have a fairly simple app, which I wrote in Clojure and would like to automatically execute one of it's functions periodically. I am trying to use Android's AlarmManager to schedule the task. This is what I have so far:

Android's Documentation for Reference enter link description here

public class HelloIntentService extends IntentService {

  /**
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }

  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
   * stops the service, as appropriate.
   */
  @Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      try {
          Thread.sleep(5000);
      } catch (InterruptedException e) {
          // Restore interrupt status.
          Thread.currentThread().interrupt();
      }
  }
}

My own progress in Clojure:

(gen-class
 :name adamdavislee.mpd.Service
 :extends android.app.IntentService
 :exposes-methods {IntentService superIntentService}
 :init init
 :prefix service)

(defn service-init []
  (superIntentService "service")
  [[] "service"])
(defn service-onHandleIntent [this i]
  (toast "hi"))

I think I'm misunderstanding something subtle; after evaluating the first sexp, the symbol adamdavislee.mpd.Service is unbound, and neither is the symbol superIntentService.


Solution

  • This code works, but only if the project is re-compiled after added the call to gen-class. gen-class can only generates classes when a project is being compiled.

    (gen-class
     :name adamdavislee.mpd.Service
     :extends android.app.IntentService
     :init init
     :state state
     :constructors [[] []]
     :prefix service-)
    (defn service-init
      []
      [["NameForThread"]
       "NameForThread"])
    (defn service-onHandleIntent
      [this i]
      (toast "service started"))