我有一個稱爲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);
}
}
}
https://developer.android.com/中有很多例子,我建議你去那裏。 –
但你能告訴我如何從其他活動調用這個方法(onLocationChanged)嗎?我找不到它在這裏:https://developer.android.com/reference/android/location/LocationListener.html#onLocationChanged(android.location.Location) – Marci
@Marci它的美是,你不打電話onLocationChanged在所有。相反,只要android設備的位置發生變化,LocationManager就會調用它。爲了實現這一點,您需要通過調用requestLocationUpdates來在LocationManager實例上設置LocationListener實例。這裏有一個例子:https://developer.android.com/guide/topics/location/strategies.html –