gpt4 book ai didi

java - Android onLocationChanged 和 MainActivity 类

转载 作者:行者123 更新时间:2023-11-30 04:01:28 25 4
gpt4 key购买 nike

我有以下代码:

public class MyLocationListener implements LocationListener {


@Override
public void onLocationChanged(Location loc) {
// called when the listener is notified with a location update from the GPS
Log.d("Latitude", Double.toString(loc.getLatitude()));
Log.d("Longitude", Double.toString(loc.getLongitude()));
}
@Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
}
@Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

在我的 MainActivity 中

            LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

现在,我只想将设备的当前位置一次接收到 MainActivity 类(获取高度和经度变量以供稍后在应用程序中使用)。

一个。如何在单次后停止接收位置?函数 lm.removeUpdates(listener) 只能在 MainActivity 类中调用。

B.基本一样。如何连接 MyLocationListener 类和 MainActivity 类?

抱歉,我是 Android 和 Java 开发的新手。谢谢!

最佳答案

您可以使用以下示例代码:

public class LocationGetter {
private final Context context;
private Location location = null;
private final Cordinate gotLocationLock = new Cordinate();
private final LocationResult locationResult = new LocationResult() {
@Override
public void gotLocation(Location location) {
synchronized (gotLocationLock) {
LocationGetter.this.location = location;
gotLocationLock.notifyAll();
Looper.myLooper().quit();
}
}
};

public LocationGetter(Context context) {
if (context == null)
throw new IllegalArgumentException("context == null");

this.context = context;
}

public void getLocation(int maxWaitingTime, int updateTimeout) {
try {
final int updateTimeoutPar = updateTimeout;
synchronized (gotLocationLock) {
new Thread() {
public void run() {
Looper.prepare();
LocationResolver locationResolver = new LocationResolver();
locationResolver.prepare();
locationResolver.getLocation(context, locationResult, updateTimeoutPar);
Looper.loop();
}
}.start();

gotLocationLock.wait(maxWaitingTime);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
gteAddress ();
}


public double getLatitude() {
return location.getLatitude();
}

public double getLongitude() {
return location.getLongitude();
}

在您的 Activity 中使用:

_locationGetter=new LocationGetter(context);

_locationGetter.getLocation(200000000, 10000000);

_locationGetter.getLongitude();

_locationGetter.getLatitude();

关于java - Android onLocationChanged 和 MainActivity 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12446742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com