2016-07-27 227 views
1

我想獲得當前的緯度和每30秒的longitutude,但我可以在每30秒鐘獲得相同的座標,但它不會改變我使用Gps服務類它低於。如何更改位置時我搬到了設備上。獲得GPS當前位置

public class GPSService extends Service implements LocationListener { 

    // saving the context for later use 
    private final Context mContext; 

    // if GPS is enabled 
    boolean isGPSEnabled = false; 
    // if Network is enabled 
    boolean isNetworkEnabled = false; 
    // if Location co-ordinates are available using GPS or Network 
    public boolean isLocationAvailable = false; 

    // Location and co-ordinates coordinates 
    Location mLocation; 
    double mLatitude; 
    double mLongitude; 

    // Minimum time fluctuation for next update (in milliseconds) 
    private static final long TIME = 30000; 
    // Minimum distance fluctuation for next update (in meters) 
    private static final long DISTANCE = 20; 

    // Declaring a Location Manager 
    protected LocationManager mLocationManager; 

    public GPSService(Context context) { 
     this.mContext = context; 
     mLocationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

    } 

    /** 
    * Returs the Location 
    * 
    * @return Location or null if no location is found 
    */ 
    public Location getLocation() { 
     try { 

      // Getting GPS status 
      isGPSEnabled = mLocationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // If GPS enabled, get latitude/longitude using GPS Services 
      if (isGPSEnabled) { 
       mLocationManager.requestLocationUpdates(
         LocationManager.GPS_PROVIDER, TIME, DISTANCE, this); 
       if (mLocationManager != null) { 
        mLocation = mLocationManager 
          .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
        if (mLocation != null) { 
         mLatitude = mLocation.getLatitude(); 
         mLongitude = mLocation.getLongitude(); 
         isLocationAvailable = true; // setting a flag that 
                // location is available 
         return mLocation; 
        } 
       } 
      } 

      // If we are reaching this part, it means GPS was not able to fetch 
      // any location 
      // Getting network status 
      isNetworkEnabled = mLocationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (isNetworkEnabled) { 
       mLocationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this); 
       if (mLocationManager != null) { 
        mLocation = mLocationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (mLocation != null) { 
         mLatitude = mLocation.getLatitude(); 
         mLongitude = mLocation.getLongitude(); 
         isLocationAvailable = true; // setting a flag that 
                // location is available 
         return mLocation; 
        } 
       } 
      } 
      // If reaching here means, we were not able to get location neither 
      // from GPS not Network, 
      if (!isGPSEnabled) { 
       // so asking user to open GPS 
       askUserToOpenGPS(); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     // if reaching here means, location was not available, so setting the 
     // flag as false 
     isLocationAvailable = false; 
     return null; 
    } 

    /** 
    * Gives you complete address of the location 
    * 
    * @return complete address in String 
    */ 
    public String getLocationAddress() { 

     if (isLocationAvailable) { 

      Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); 
      // Get the current location from the input parameter list 
      // Create a list to contain the result address 
      List<Address> addresses = null; 
      try { 
       /* 
       * Return 1 address. 
       */ 
       addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1); 
      } catch (IOException e1) { 
       e1.printStackTrace(); 
       return ("IO Exception trying to get address:" + e1); 
      } catch (IllegalArgumentException e2) { 
       // Error message to post in the log 
       String errorString = "Illegal arguments " 
         + Double.toString(mLatitude) + " , " 
         + Double.toString(mLongitude) 
         + " passed to address service"; 
       e2.printStackTrace(); 
       return errorString; 
      } 
      // If the reverse geocode returned an address 
      if (addresses != null && addresses.size() > 0) { 
       // Get the first address 
       Address address = addresses.get(0); 
       /* 
       * Format the first line of address (if available), city, and 
       * country name. 
       */ 
       String addressText = String.format(
         "%s, %s, %s", 
         // If there's a street address, add it 
         address.getMaxAddressLineIndex() > 0 ? address 
           .getAddressLine(0) : "", 
         // Locality is usually a city 
         address.getLocality(), 
         // The country of the address 
         address.getCountryName()); 
       // Return the text 
       return addressText; 
      } else { 
       return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it."; 
      } 
     } else { 
      return "Location Not available"; 
     } 

    } 



    /** 
    * get latitude 
    * 
    * @return latitude in double 
    */ 
    public double getLatitude() { 
     if (mLocation != null) { 
      mLatitude = mLocation.getLatitude(); 
     } 
     return mLatitude; 
    } 

    /** 
    * get longitude 
    * 
    * @return longitude in double 
    */ 
    public double getLongitude() { 
     if (mLocation != null) { 
      mLongitude = mLocation.getLongitude(); 
     } 
     return mLongitude; 
    } 

    /** 
    * close GPS to save battery 
    */ 
    public void closeGPS() { 
     if (mLocationManager != null) { 
      mLocationManager.removeUpdates(GPSService.this); 
     } 
    } 

    /** 
    * show settings to open GPS 
    */ 
    public void askUserToOpenGPS() { 
     AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext); 

     // Setting Dialog Title 
     mAlertDialog.setTitle("Location not available, Open GPS?") 
     .setMessage("Activate GPS to use use location services?") 
     .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       mContext.startActivity(intent); 
       } 
      }) 
      .setNegativeButton("Cancel",new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.cancel(); 
        } 
       }).show(); 
    } 

    /** 
    * Updating the location when location changes 
    */ 
    @Override 
    public void onLocationChanged(Location location) { 
     mLatitude = location.getLatitude(); 
     mLongitude = location.getLongitude(); 
    } 

    @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; 
    } 

} 

和我打電話的getLocation方法MYCLASS

double latitudem2, longitudem2; 
String cnvrt_latitude2,cnvrt_longitude2; 

if (mGPSService2.isLocationAvailable == false) { 

     cnvrt_latitude2 = "0"; 
     cnvrt_longitude2 = "0"; 

     // Or you can continue without getting the location, remove the return; above and uncomment the line given below 
     // address = "Location not available"; 
    } else { 


     mGPSService2.getLocation(); 


     // Getting current location co-ordinates 
     latitudem2 = mGPSService2.getLatitude(); 
     longitudem2 = mGPSService2.getLongitude(); 
     //Toast.makeText(getApplicationContext(), "Latitude:" + latitudem + " | Longitude: " + longitudem, Toast.LENGTH_LONG).show(); 

     cnvrt_latitude2 = String.valueOf(latitudem2); 
     cnvrt_longitude2 = String.valueOf(longitudem2); 

    } 

回答

0

我使用了不同的方法。我認爲你應該使用谷歌播放。

dependencies { 
.. 
compile 'com.google.android.gms:play-services:8.4.0' 
.. 
} 

,並在您的活動:

private void initGoogleClient() { 
    googleClient = new GoogleApiClient.Builder(this) 
     .addConnectionCallbacks(this) 
     .addOnConnectionFailedListener(this) 
     .addApi(LocationServices.API) 
     .build(); 
} 

,然後註冊您的應用程序:

LocationRequest req = new LocationRequest(); 
req.setInterval(60 * 60 * 1000); 
req.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
LocationServices.FusedLocationApi.requestLocationUpdates(googleClient, req, this); 

您可以根據您的要求更改優先級。 不要忘記實現您的活動聽衆

public class MainActivity extends AppCompatActivity 
     implements GoogleApiClient.OnConnectionFailedListener, 
        GoogleApiClient.ConnectionCallbacks, 
        LocationListener { 
... 
} 

我提出了類似根據當前位置要知道紫外線指數東西。你可以看看我的post

+0

當我運行我的方法,它的工作原理,當我移動到手機的緯度和經度改變,我的手機哪個android 5.0,但是當我嘗試我的平板電腦哪些android 4.2的位置不變。你有這個問題的想法嗎? – Diego

+0

聽起來有點奇怪..你可以嘗試使用我的代碼,並檢查它是否工作。對我來說,它運作良好。 – FrancescoAzzola