ネットワークまたは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;
}
どれだけ待っても、アプリは場所を教えてくれません。
このコードの何が問題で、どうすれば修正できますか?