2013-07-16 60 views
13

我的应用程序启动时只需要粗略位置服务。如何使用Wifi或GSM或GPS获取粗略位置?

详细地说,我需要该应用程序的粗略位置,以便为用户提供附近的商店信息。

该位置不需要不断更新。另外,在这种情况下,粗定位就足够了。

我希望应用程序自动选择GSM,或wifi或GPS,无论哪一个可用。

位置服务也应该是一次性节省电话能量

我该怎么做?

我已经尝试过单独使用GPS。

我的问题是我不知道如何停止GPS的不断刷新位置功能。我不知道如何让手机从三种方法中选择一种。

一些示例代码或想法非常感谢。

+1

locationManager.requestLocationUpdates()方法需要最小距离和最小时间,然后再尝试再次请求位置。使用您需要的值。当你使用它时,取消注册接收器以停止更新。 –

回答

17

这里的某种观点:

private void _getLocation() { 
    // Get the location manager 
    LocationManager locationManager = (LocationManager) 
      getSystemService(LOCATION_SERVICE); 
    Criteria criteria = new Criteria(); 
    String bestProvider = locationManager.getBestProvider(criteria, false); 
    Location location = locationManager.getLastKnownLocation(bestProvider); 
    try { 
     lat = location.getLatitude(); 
     lon = location.getLongitude(); 
    } catch (NullPointerException e) { 
     lat = -1.0; 
     lon = -1.0; 
    } 
} 

这可能不过要求FINE_LOCATION访问。所以:

另一种方法是使用this,它使用LocationManager

最快的方式是与此使用的最后已知位置,我用它和它的相当快:

private double[] getGPS() { 
LocationManager lm = (LocationManager) getSystemService(
    Context.LOCATION_SERVICE); 
List<String> providers = lm.getProviders(true); 

Location l = null; 

for (int i=providers.size()-1; i>=0; i--) { 
    l = lm.getLastKnownLocation(providers.get(i)); 
    if (l != null) break; 
} 

double[] gps = new double[2]; 
if (l != null) { 
    gps[0] = l.getLatitude(); 
    gps[1] = l.getLongitude(); 
} 

return gps; 
} 
1

为了从特定供应商处获得信息,您应该使用:LocationManager.getLastKnownLocation(String provider),如果您希望自己的应用在供应商之间自动选择,那么您可以使用getBestProvider方法添加供应商的选择。至于停止GPS位置的刷新,我不太明白。你只需要获取位置信息一次,还是需要定期监测位置变化?

编辑:哦,对了,如果你希望你的位置信息,以达到最新的,你应该使用位置经理requestSingleUpdate方法,用指定的标准。在这种情况下,供应商也应该自动选择

+0

只有一次。即应用程序仅在首次启动时估计位置。稍后用户可以手动选择刷新该位置 –

7

这是一种方式

public class GPSTracker extends Service implements LocationListener { 

    private final Context mContext; 

    // flag for GPS status 
    boolean isGPSEnabled = false; 

    // flag for network status 
    boolean isNetworkEnabled = false; 

    // flag for GPS status 
    boolean canGetLocation = false; 

    Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

    // Declaring a Location Manager 
    protected LocationManager locationManager; 

    public GPSTracker(Context context) { 
     this.mContext = context; 
     getLocation(); 
    } 

    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) mContext 
        .getSystemService(LOCATION_SERVICE); 

      // getting GPS status 
      isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
       // if GPS Enabled get lat/long using GPS Services 
       if (isGPSEnabled) { 
        if (location == null) { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
          } 
         } 
        } 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return location; 
    } 

    /** 
    * Stop using GPS listener 
    * Calling this function will stop using GPS in your app 
    * */ 
    public void stopUsingGPS(){ 
     if(locationManager != null){ 
      locationManager.removeUpdates(GPSTracker.this); 
     }  
    } 

    /** 
    * Function to get latitude 
    * */ 
    public double getLatitude(){ 
     if(location != null){ 
      latitude = location.getLatitude(); 
     } 

     // return latitude 
     return latitude; 
    } 

    /** 
    * Function to get longitude 
    * */ 
    public double getLongitude(){ 
     if(location != null){ 
      longitude = location.getLongitude(); 
     } 

     // return longitude 
     return longitude; 
    } 

    /** 
    * Function to check GPS/wifi enabled 
    * @return boolean 
    * */ 
    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    /** 
    * Function to show settings alert dialog 
    * On pressing Settings button will lauch Settings Options 
    * */ 
    public void showSettingsAlert(){ 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

     // Setting Dialog Title 
     alertDialog.setTitle("GPS is settings"); 

     // Setting Dialog Message 
     alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 

     // On pressing Settings button 
     alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog,int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       mContext.startActivity(intent); 
      } 
     }); 

     // on pressing cancel button 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 
      } 
     }); 

     // Showing Alert Message 
     alertDialog.show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

} 

使用这种方式:

gps = new GPSTracker(PromotionActivity.this); 

// check if GPS enabled  
if(gps.canGetLocation()){ 
    double latitude = gps.getLatitude(); 
    double longitude = gps.getLongitude(); 
}else{ 
// can't get location 
// GPS or Network is not enabled 
// Ask user to enable GPS/network in settings 
    gps.showSettingsAlert();  
} 

使用这个,你可以得到最好的位置。希望帮助

+0

需要小心以“this”关键字以便从其他Activity中调用需要替换为“mContext” – Sam