gpt4 book ai didi

android - 从服务获取位置数据?

转载 作者:行者123 更新时间:2023-11-29 21:49:53 24 4
gpt4 key购买 nike

我尝试提供定位服务,但不知何故我无法让它工作。Lat 和 Lng 始终为 NULL。

我在 locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener); 上有一些异常,所以我把它放在 run() 方法中,现在是异常离开了。可能是什么问题?

那么使定位服务发挥作用的解决方案是什么?

代码:

public class LocationService extends Service {

private Timer timer = new Timer();

private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();

private String latitude;
private String longitude;
private String providerToSend;

Messenger messenger;
Timer t = new Timer();

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

public void onCreate() {
super.onCreate();

locListener = new MyLocationListener();
locationProviderInit();
startService();

}

@Override
public void onDestroy() {
super.onDestroy();
shutdownService();

}

private void startService() {


locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

String token = new SharedPreffer(this).loadPreferences("token");

Log.d("Debug - token: ", "Van Token: " + token);

t.schedule(new TimerTask() {

@Override
public void run() {

locationProviderInit();

if (latitude != null && longitude != null) {

Log.d("Debug - lat: ", latitude);
Log.d("Debug - lng: ", longitude);

} else {

Log.d("Debug - lat and lng are: ", "NULL");
}

}
}, 0, 5000);

}

private void locationProviderInit() {

new Runnable() {

@Override
public void run() {

try {

boolean gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
providerToSend = LocationManager.GPS_PROVIDER;
}

if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
providerToSend = LocationManager.NETWORK_PROVIDER;
}

} catch (Exception e) {
Log.d("Debug", e.toString());
}
}
};

}


class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {

if (location != null) {
longitude = Double.toString(location.getLongitude());
latitude = Double.toString(location.getLatitude());
}
}

public void onProviderDisabled(String arg) {
}

public void onProviderEnabled(String arg) {
}

public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

private void shutdownService() {
if (timer != null)
timer.cancel();
Log.i(getClass().getSimpleName(), "Timer stopped!!!");
}

}

最佳答案

你没有在 locationProviderInit 中执行 Runnable...

关于android - 从服务获取位置数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14688863/

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