Android Gps当前定位问题

Android Gps当前定位问题,android,Android,我的Gps设置在一开始是“关闭”的,我执行了这个代码,我可以得到当前位置的纬度和经度 但一旦我按程序打开,设置就改变了,一切都很好 当我再次执行时,它没有给我(提供者、位置引用),我不明白为什么会发生这种情况 public void getCurrentlocation() { String providers = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALL

我的Gps设置在一开始是“关闭”的,我执行了这个代码,我可以得到当前位置的纬度和经度

但一旦我按程序打开,设置就改变了,一切都很好

当我再次执行时,它没有给我(提供者、位置引用),我不明白为什么会发生这种情况

 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!");
 }
    }
public void getCurrentlocation()
{
String providers=Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION\u providers\u允许);
Log.e(“提供者”,提供者);
如果(!providers.contains(“gps”)){
最终意图=新意图();
poke.setClassName(“com.android.settings”、“com.android.settings.widget.SettingsAppWidgetProvider”);
poke.addCategory(意向、类别和备选方案);
setData(Uri.parse(“3”);
发送广播(poke);
Log.e(“您的gps已启用”);
}
locationManager=(locationManager)getSystemService(Context.LOCATION\u服务);
//定义如何选择位置提供程序->使用的条件
//违约
标准=新标准();
字符串提供程序=locationManager.getBestProvider(条件为true);
Location Location=locationManager.getLastKnownLocation(提供者);
//初始化位置字段
如果(位置!=null)
{
System.out.println(“已选择提供程序”+提供程序+”);
strLatitude=String.valueOf(location.getLatitude());
strlongitute=String.valueOf(location.getLongitude());
Log.e(“格度”,标准度);
Log.e(“logntitude”,strLongitude);
}
其他的
{
strLatitude=String.valueOf(0);
strlongite=String.valueOf(0);
Log.e(“格度”,标准度);
Log.e(“logntitude”,strLongitude);
}
Geocoder Geocoder=新的地理编码器(this,Locale.ENGLISH);
试一试{
列表地址=geocoder.getFromLocation(Double.parseDouble(strLatitude),Double.parseDouble(strlongite),5);
getAddress(Double.parseDouble(strLatitude)、Double.parseDouble(strLongitude));
如果(地址!=null){
返回的地址地址=地址。获取(0);
StringBuilder strReturnedAddress=新StringBuilder(“地址:\n”);
对于(inti=0;i试试这个

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;
}
按如下方式调用上述方法。如果此处的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();
}

您正在查找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));

    }

}