-1

我的 Gps 设置一开始是“关闭”的,我执行了这段代码,我可以得到 CurrentLocation 的纬度和经度。

但是一旦我以编程方式打开,设置就会改变,一切都很好。

当我再次执行时,它没有给我(提供者、位置参考),我不明白为什么会这样。

 public void getCurrentlocation()
{
    String providers = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    Log.e("provider",providers);
    if(!providers.contains("gps")){
      final Intent poke = new Intent();
      poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
      poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
      poke.setData(Uri.parse("3")); 
      sendBroadcast(poke);
      Log.e("your gps is","enabled");
    }
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
       // Define the criteria how to select the locatioin provider -> use
       // default
       Criteria criteria = new Criteria();
       String provider = locationManager.getBestProvider(criteria,true);
       Location location = locationManager.getLastKnownLocation(provider);

       // Initialize the location fields
       if (location != null) 
       {
        System.out.println("Provider " + provider + " has been selected.");
              strLatitude=String.valueOf(location.getLatitude());
              strLongitude=String.valueOf(location.getLongitude());
              Log.e("lattitude",strLatitude);
              Log.e("logntitude",strLongitude);
       }
       else 
       {
              strLatitude=String.valueOf(0);
              strLongitude=String.valueOf(0);
              Log.e("lattitude",strLatitude);
              Log.e("logntitude",strLongitude);
       }

       Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);

       try {
  List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(strLatitude), Double.parseDouble(strLongitude), 5);
 getAddress(Double.parseDouble(strLatitude), Double.parseDouble(strLongitude));
  if(addresses != null) {
   Address returnedAddress = addresses.get(0);
   StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
   for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
   }
   Log.e("address",strReturnedAddress.toString());
  }
  else{
   Log.e("not found","No Address returned!");
  }
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  Log.e("cannot get address","Canont get Address!");
 }
    }
4

2 回答 2

0

您正在寻找 lastKnownlocation,如果设备有任何 lastknownlocation(如果 GPS 已打开),它将为您提供,然后它将寻找新位置并且 lastKnownlocation 可能为空。

您应该实现 LocationListner。尝试使用这个:

公共类 GetLocationUpdate {

LocationManager locationManager;
LocationListener locationListner;
LinearLayout linearLayout;
TextView locLat, locLong, locInfo;
LocationProvider locationProvider;
private Context context;

/* public double mLattitude = 28.618527, mLongitude = 77.372642; */

public double mLattitude = 0.0, mLongitude = 0.0;
public static GetLocationUpdate getLocationUpdateInstance;

public static GetLocationUpdate getLocationUpdateInstance(Context context)
{
    getLocationUpdateInstance = new GetLocationUpdate(context);
    return getLocationUpdateInstance;
}

private GetLocationUpdate(Context context)
{
    this.context = context;

    locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

    locationListner = new MyLocationListner();
}

public static Criteria createCoarseCriteria()
{

    Criteria c = new Criteria();
    c.setAccuracy(Criteria.ACCURACY_COARSE);
    c.setAltitudeRequired(false);
    c.setBearingRequired(false);
    c.setSpeedRequired(false);
    c.setCostAllowed(true);
    c.setPowerRequirement(Criteria.POWER_HIGH);
    return c;

}

/** this criteria needs high accuracy, high power, and cost */
public static Criteria createFineCriteria()
{

    Criteria c = new Criteria();
    c.setAccuracy(Criteria.ACCURACY_FINE);
    c.setAltitudeRequired(false);
    c.setBearingRequired(false);
    c.setSpeedRequired(true);
    c.setCostAllowed(true);
    c.setPowerRequirement(Criteria.POWER_HIGH);
    return c;

}

public void startLocationListner()
{

    try
    {

        locationManager.requestLocationUpdates(

        LocationManager.GPS_PROVIDER, 1000, 0, locationListner);

        mLattitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude();
        mLongitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude();
    }
    catch (Exception e)
    {
        // e.printStackTrace();
    }

    try
    {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListner);
        if (mLattitude == 0.0 || mLongitude == 0.0)
        {
            mLattitude = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLatitude();
            mLongitude = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLongitude();
        }
    }
    catch (Exception e)
    {
        // e.printStackTrace();
    }

    Log.w("value : ",
            String.valueOf(mLattitude) + ":" + String.valueOf(mLongitude));

}

public void stopLocationListner()
{
    if (locationListner != null)
    {

        locationManager.removeUpdates(locationListner);
        locationListner = null;
    }
}

private class MyLocationListner implements LocationListener
{

    @Override
    public void onLocationChanged(Location location)
    {

        mLattitude = location.getLatitude();
        mLongitude = location.getLongitude();

        Log.w("value : ",
                String.valueOf(location.getLatitude()) + String.valueOf(location.getLongitude())
                        + 


        context.sendBroadcast(new Intent(Constants.BRDCAST_LOCATION_UPDATED));

    }

    @Override
    public void onProviderDisabled(String provider)
    {
        // Log.w("provider", provider);

    }

    @Override
    public void onProviderEnabled(String provider)
    {
        // Log.w("provider", provider);

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras)
    {
        // Log.w("status", String.valueOf(status));

    }

}

}

于 2013-01-20T14:25:25.457 回答
0

尝试这个。

Location getGPSLocation(Context context) {
    try {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria cr = new Criteria();
        cr.setCostAllowed(true);
        cr.setAccuracy(Criteria.NO_REQUIREMENT);
        cr.setPowerRequirement(Criteria.NO_REQUIREMENT);
        String provider = lm.getBestProvider(cr, true);
        if(provider == null)
            provider = lm.getBestProvider(cr, false);
        return lm.getLastKnownLocation(provider);
    }
    catch(Exception e) {
        Log.e("NeartoMe", "Exception while fetch GPS at: " + e.getMessage());
    }
    return null;
}

像这样调用上面的方法。如果在这里您得到空值,则意味着获取 gps 时出现问题,然后重定向以启用位置和安全设置中的“使用无线网络”。然后再次尝试获取 GPS。

Location location = new Helper().getGPSLocation(context);
if(location != null) {
    latitude = (int) (location.getLatitude() * 1E6);
    longitude = (int) (location.getLongitude() * 1E6);
} else {
    Builder alert = new Builder(context);
    alert.setTitle(R.string.app_name);
    alert.setMessage(context.getString(R.string.enable_use_wireless_network));
    alert.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() 
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            dialog.dismiss();
            context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    });
    alert.show();
}
于 2013-01-20T13:02:26.913 回答