您好我已经实现了一个广播当前位置的服务。事情是第一次更新它给我0.0 lat和0.0 lon,这破坏了UI。我可以解决这个问题吗? 这是代码,谢谢
public class LocationService extends Service {
protected LocationManager locationManager;
final static String MY_ACTION = "MY_ACTION";
MyLocListener myloc = new MyLocListener();
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override public void onDestroy() {
};
@Override
public int onStartCommand(Intent intent, int flags, int startId){
final Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(true);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
LocationListener ll = new MyLocListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 0, ll);
Location location = new Location("abc");
ll.onLocationChanged(location);
Log.d("Last", ""+location.getLatitude());
return START_STICKY;
}
private class MyLocListener implements LocationListener {
public void onLocationChanged(Location location) {
Log.d("1provider",location.toString());
Log.d("1Provider LOCATION CHANGED", location.getLatitude() + "");
Log.d("1Provider LOCATION CHANGED", location.getLongitude() + "");
Intent intent = new Intent();
intent.putExtra("location", location);
intent.setAction(MY_ACTION);
sendBroadcast(intent);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Log.d("1Provider DIsabled", "Provider Disabled");
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d("1Provider Enabled", "Provider Enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.d("1Provider Changed", "Service Status Changed");
}
}
}
答案 0 :(得分:0)
onLocationChanged()方法通常在第一次返回0 - 只检查此值并且不更新UI。至于花费太长时间,可能需要一段时间,因此在获取位置时将服务作为AsyncTask运行,以便您的UI线程等待,然后在从AsyncTask返回时更新UI。