我需要通过网络或 gps 找到当前位置。
我通过互联网和 stackoverflow 进行了搜索,但我找不到这段代码有什么问题。
我还在清单中设置了这个参数:
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
所以这是我的代码:
LocationManager locationManager;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
findCurrentLocation();
//some other stuff here
}
public void findCurrentLocation()
{
boolean networkEnabled = false;
boolean gpsEnabled = false;
currentLocation = getLastKnownLocation();
if(currentLocation == null)
{
currentLocation = new Location("sometext");
locationFindDialog = ProgressDialog.show(this, "Find Your Location", "Please Wait", false);
try
{
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch(Exception e)
{
}
try
{
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception e)
{
}
if((networkEnabled == false) && (gpsEnabled == false))
{
locationFindDialog.dismiss();
showMessage("we need gps or sim card(or network) to find your location");
//show message
//you need at least one provider
return;
}
if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
}
if(gpsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
}
}
private final LocationListener networkLocationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
currentLocation.set(location);
//unregister listener
locationManager.removeUpdates(this);
locationManager.removeUpdates(gpsLocationListener);
locationFindDialog.dismiss();
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
private final LocationListener gpsLocationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
currentLocation.set(location);
//unregister listener
locationManager.removeUpdates(this);
locationManager.removeUpdates(networkLocationListener);
locationFindDialog.dismiss();
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
private Location getLastKnownLocation()
{
Location location = null;
List<String> providers = locationManager.getAllProviders();
for(String provider : providers)
{
location = locationManager.getLastKnownLocation(provider);
if(location != null)
{
return location;
}
}
return null;
}
不管我等了多久,应用程序都不给我位置。
这段代码有什么问题,我该如何解决?