当我有经度和纬度坐标时,我想使用谷歌天气api获取天气信息。所以我采取的代码:
private void updateWeather(){
new Thread(){
public void run() {
//get Weather start:
LocationHelper helper = new LocationHelper(MomentsActivity.this);
Location location = helper.getLocation();
if(null != location){
String request = "http://www.google.com/ig/api?weather=,,,"+location.getLatitude()
+","+location.getLongitude();
XmlParserUtil parser = new XmlParserUtil(mHandler);
try {
parser.parse(HttpUtil.getWeather(request));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//end
};
}.start();
}
但是当我想从LocationManager获得经度和纬度时,我发现该位置始终为空。请参阅获取位置的代码:
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
public class LocationHelper {
Context context;
public LocationHelper(){}
public LocationHelper(Context context){
this.context = context;
}
public Location getLocation(){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(null == location){
location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
return location;
}
}
请帮我找到错误。谢谢。
另外: 我添加了一些权限:
<uses-permission android:name="android.permission.INTERNET" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" ></uses-permission>
同样,我打开了GPS和wifi,但位置也是空的。
答案 0 :(得分:0)
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
System.out.println("Location is: :" + location.toString());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
// locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListener);
你可以得到比这更好的东西。例如,连续运行位置代码应该是一个很大的电池消耗。您还需要收听多个响应并过滤以确定准确性和近期性之间的优先级。祝你好运。