2017-09-18 33 views
0

我有一個稱爲GPS_Service的服務。 從另一個活動我想開始此服務,並從onLocationChanged()方法獲取location.getLatitude()和location.getLongitude()的值。如果onLocationChanged()不是靜態的,我怎麼能這樣做?從onLocationChanged方法獲取服務的經度/緯度

在此先感謝!

public class GPS_Service extends Service { 

private LocationListener listener; 
private LocationManager locManager; 

@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onCreate() { 
    liveLocs = new ArrayList<>(); 
    if (PreferenceManager.getDefaultSharedPreferences(GPS_Service 
      .this).getString("len_live_locations", "-") != "-") { 

    } 

    listener = new LocationListener() { 
    @Override 
     public void onLocationChanged(Location location) { 
      Intent i = new Intent("location_update"); 
      i.putExtra("coordinates", location.getLongitude() + "  " + location 
        .getLatitude()); 
      sendBroadcast(i); 
     } 
    } 
} 
+0

https://developer.android.com/中有很多例子,我建議你去那裏。 –

+0

但你能告訴我如何從其他活動調用這個方法(onLocationChanged)嗎?我找不到它在這裏:https://developer.android.com/reference/android/location/LocationListener.html#onLocationChanged(android.location.Location) – Marci

+1

@Marci它的美是,你不打電話onLocationChanged在所有。相反,只要android設備的位置發生變化,LocationManager就會調用它。爲了實現這一點,您需要通過調用requestLocationUpdates來在LocationManager實例上設置LocationListener實例。這裏有一個例子:https://developer.android.com/guide/topics/location/strategies.html –

回答

1

在服務試試這個:嘗試使用Bundle

Intent intent = new Intent("YourAction"); 
Bundle bundle = new Bundle(); 
bundle.put... // put extras you want to pass with broadcast. This is optional 
bundle.putString("valueName", "The value you want in the activity"); 
bundle.putDouble("doubleName", someDouble); 
intent.putExtras(bundle) 
LocalBroadcastManager.getInstance(context).sendBroadcast(intent); 
+0

「intent.putExtras(意圖)」我不明白這一點,你爲什麼把意圖本身? – Marci

+0

我認爲這只是一個很小的錯誤。而不是intent.putExtras(intent)它應該是intent.putExtras(bundle) –

+0

我明白了,謝謝。但好的,這段代碼片段在我的onLocationChanged方法中。但是,我如何從其他活動中獲得該包? – Marci

0

這可以得到令人難以置信的令人費解。您必須決定您將使用哪種類型的位置提供商,獲取權限,檢查是否安裝了Google Play服務以及所需的正確版本,當然還有位置管理器與融合位置管理器等的後備選項。

我花了很多時間在監控位置周圍編寫圖書館,並且它可能會耗費大量時間,並且維護有時可能會有點痛苦。

所以這裏是我會推薦的。你提到「服務」我不知道你是否真的需要這樣做,但你可以做三件事之一。

  1. 管理位置有一個單包裝
  2. 創建IntentService讓你的位置,是令人滿意的準確度範圍內考慮那麼做廣播使用自定義廣播接收器收到你的變化
  3. 創建一個普通的Android服務,它可以繼續更新位置並根據需要從後臺將其反饋給您,在後臺您需要綁定到此服務,並由您來決定啓動和停止它。但是,請記住,在後臺收集位置方面存在限制,現在可能需要在任務欄中發出粘性通知。

我建議你先用簡單回調的單例包裝器中的一個好庫開始,然後從那裏工作到服務包裝器。我個人喜歡這個圖書館的位置更新。

https://github.com/mrmans0n/smart-location-lib

工作得很好。祝你好運。