2010-10-14 78 views
0

我有一個android服務在後臺運行,每隔幾秒就會從服務器接收座標。我不確定每當服務收到服務器的響應時,我如何在地圖上顯示座標。善意幫助或給出一個想法。就隨時更新地圖上顯示的位置服務在地圖上顯示點android

感謝

回答

1

我不知道任何這教程,但這裏有一個版本,我的:

要發送廣播,使用Context類的「sendBroadcast(意向I)」的方法。 Service類擴展了Context,所以你可以從你的實現中訪問它。

因此,在您服務雲:

public static final String BROADCAST_ACTION="com.yourservice.update"; 

public void onStart(Intent intent, int startId) { 
... 
Intent broadcastIntent = new Intent(BROADCAST_ACTION); 
    sendBroadcast(broadcastIntent); 
... 
} 

你要註冊這個廣播接收器在你的活動(你啓動boradcasting他們可能以前),像這樣:

private BroadcastReceiver receiver=new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 

         //Here goes handling the stuff you got from the service 
    Bundle extras = intent.getExtras(); 
    if(extras != null)processUIUpdate(extras); 
    } 
}; 

public void onResume() { 
... 
//Register for the update broadcasts from the torrent service 
registerReceiver(receiver, new IntentFilter(YourService.BROADCAST_ACTION)); 
... 
} 

別當活動進行到後臺時,忘記取消註冊:

public void onPause() { 
... 
    //Deregister for the update broadcast from the torrent service 
    unregisterReceiver(receiver); 
... 
} 

這應該有效。

+0

非常感謝你的示例代碼Scythe。現在該服務是否會自動首次啓動活動並開始廣播點數?或者活動必須由我們開始,之後它等待接收意圖並顯示。 另外,我如何刷新活動以顯示新數據。你能解釋一下嗎? – 2010-10-15 20:55:32

+0

當您的活動開始時,您註冊BroadcastReceiver。然後,您啓動開始發送這些廣播的服務。所以不,服務不會啓動你的活動,這是相反的。 (實際上,你也可以實現這種行爲,但不推薦)你的自定義BroadcastReceiver實現(你在Activity啓動時註冊的實現)可以是Activity中的內部類。因此,在onReceive()回調中,您可以根據您從廣播消息中獲取的信息更新Activity的UI。 – 2010-10-16 08:55:36

+0

謝謝鐮刀。我能夠實現它的效果很好。但是,如何每十秒播出一次意圖呢?服務必須每隔10秒輪詢一次服務器並在地圖上顯示這些點。我試圖使用AlarmManager類,但無法弄清楚..任何建議? – 2010-10-17 21:46:23

1

您的服務可以廣播意圖。顯示地圖的活動應爲該boradcast註冊一個接收器,而boradcast的意圖可以保存lat的值。和長。

+0

謝謝你的概念鐮刀。但我看到BroadCast是一個類而不是接口。如何能夠在服務中使用它? – 2010-10-15 00:35:18

+0

你是否知道這樣做的任何教程 – 2010-10-15 00:37:15