2017-10-09 72 views
2

我有一個相當簡單的應用程序,我在Clojure中編寫並希望定期自動執行其中一個功能。我正在嘗試使用Android的AlarmManager來安排任務。這是我到目前爲止有:在Clojure中創建一個Android服務

Android的文檔爲參考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(); 
     } 
    } 
} 

我用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")) 

我想我誤解的東西微妙;在評估第一個sexp後,符號adamdavislee.mpd.Service未被綁定,並且符號superIntentService也不是。

回答

0

此代碼有效,但只有在將該項目添加到gen-class之後重新編譯該項目。 gen-class只能在編譯項目時生成類。

(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")) 
1

將基於閱讀你的代碼的一些建議(即不知道如果這些將工作)

它看起來像你可能對Java的互操作問題。你可以看到更多的信息here。它看起來像:prefix也應該是一個字符串。例如

(gen-class 
:name adamdavislee.mpd.Service 
:extends android.app.IntentService 
:exposes-methods {IntentService superIntentService} 
:init init 
:prefix "service-") ;;---> make this a string and append '-' 

(defn service-init [] 
    (.superIntentService "service");;-> update with prepend dot-notation for Java interop 
    [[] "service"])    ;;-> not sure what 'service' is doing here 
           ;; perhaps consider an atom 
(defn service-onHandleIntent [this i] 
    (.toast "hi")) ;;=> Not sure where this method is coming from, 
        ;; but guessing java interop need here as well 

This example也可能提供一些有用的見解。希望這有助於...

+0

謝謝;現在我越來越近了,特別是它幫助我們認識到'superIntentService'是作爲一種方法公開的,而不是一個普通的符號。 –