0

我想定期將我的用戶位置更新到Google App Engine中的Google Endpoint。
我使用端點的事實很重要,因爲這就是爲什麼我不能簡單地使用IntentServiceAlarmManger來安排任務。使用端點定期更新userpositon到服務器

問題是以下幾點:
要更新位置到服務器,我需要一些在服務中無法訪問的對象。
讓我試着勾畫它:

public class MyService extends IntentService { 
    [...] 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     endpointsHandler.updatePosition() 
     return super.onStartCommand(intent, flags, startId); 
    } 
} 

在這裏,我需要我的EndpointsHandler的對象。我不能簡單地創建一個新對象,因爲它取決於其他一些對象,如GoogleApiClient

但我不能對象添加到服務器,因爲當我初始化AlarmManager沒有辦法傳遞對象

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
Intent updaterIntent = new Intent(this, MyService.class); 
PendingIntent pendingIntent = PendingIntent.getService(this, 0, updaterIntent, 0); 
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SOME_PERIOD, SOME_PERIOD, pendingIntent); 

我可以傳遞的對象作爲意圖,但除了一個事實,即所有類(即使GoogleApiClient)也得執行Parceable,我不這件事是一個很好的方法。我確信有一種乾淨的方式,我無法找到。

+0

將這些對象序列化不是一個好主意,因爲它們可能包含不可序列化的內容。你爲什麼不創建一個新的GoogleApiClient? –

+0

創建一個新的GoogleApiClient將是可能的,但這將是一個非常糟糕的方式,因爲創建需要很長時間,並且需要很多資源才能在非常時期創建新對象。 – 0xAffe

回答

0

我自己解決了它。
但是因爲我沒有在SO上找到任何這樣的解決方案,所以我會在這裏發佈它:

我使用了描述的方式here。 我創建了一箇中央控制器類,它保留了我的應用程序的所有重要對象。這個類是android.app.Application的一個子類。
在清單,文件我加

<application 
    [...] 
    android:name=".controllers.AppController"> 

要聲明使用我的自定義應用程序類。
現在在每個活動和服務中,我可以使用getApplication()來獲取我的應用程序類的對象。

相關問題