2015-10-01 60 views
0

當天的問候。我正在開發應用程序,我需要顯示地圖。 我想要一個地圖在我目前的位置默認顯示,但我無法這樣做。我嘗試了幾種方法獲取當前位置(LatLng)。 我也跟着這個link,當我從Android設備監視器發送LatLng但在真實設備上失敗時,鏈接在仿真器上正常工作。無法在android中獲取當前位置

,寫了一段簡單的代碼下面

Location myLoc=mMap.getMyLocation(); 
    double cLat=myLoc.getLatitude(); 
    double cLng=myLoc.getLongitude(); 
    showMap(cLat,cLng); 

給出上述代碼返回NULL。被困住了。請幫助

回答

6

創建一個類GpsTracker.java:

import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.GpsStatus; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.util.Log; 

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 = 1000; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 100000 * 60 * 1; // 5 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 
       //showSettingsAlert(); 

      } else { 
       this.canGetLocation = true; 
       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 
       else { 
        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(); 
      System.exit(0); 

      } 
     }); 

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

} 

現在,您可以獲取位置創建實例GpsTracker.java,如:

GPSTracker gpstracker=new GPSTracker(EditProfile.this); 
double lat=gpstracker.getLatitude(); 
double longitude=gpstracker.getLongitude(); 

你也可以檢查FusedLocationApi獲取當前緯度和經度.FusedLocationApi比以前的方法消耗更少的電池。

請務必爲這兩種情況開啓您的位置服務。

+0

感謝您的迴應..但它應該是gpstracker在第二段代碼的第二行嗎? – Brucode

+0

對不起我的錯誤...更正.. – kgandroid

+0

謝謝你這麼多:)我嘗試了很多方法,但是這個最終工作。再次感謝 – Brucode

1

您應該處理位置爲空的情況,並回退到合理的默認值,例如將主要城市的地圖居中。谷歌的文件指出,地點can be null in rare cases。在實踐中,我發現這種情況經常發生在設備長時間呆在室內或禁用了位置服務時。

1
public class SplashScreen extends Activity implements GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener { 

    // LogCat tag 
    private static final String TAG = MainActivity.class.getSimpleName(); 

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; 

    private Location mLastLocation; 

    // Google client to interact with Google API 
    private GoogleApiClient mGoogleApiClient; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.splash_screen); 
     CheckGPS(); 

     ImageView textView = (ImageView) findViewById(R.id.center); 
     Animation logoMoveAnimation = AnimationUtils.loadAnimation(this, R.anim.splash); 
     textView.startAnimation(logoMoveAnimation); 


    } 

    private void setUpLocation() { 
     // First we need to check availability of play services 
     if (checkPlayServices()) { 
      // Building the GoogleApi client 
      buildGoogleApiClient(); 
     } 
    } 


    /** 
    * Method to display the location on UI 
    */ 
    private void displayLocation() { 

     mLastLocation = LocationServices.FusedLocationApi 
       .getLastLocation(mGoogleApiClient); 

     if (mLastLocation != null) { 
      double latitude = mLastLocation.getLatitude(); 
      double longitude = mLastLocation.getLongitude(); 
      getCities(latitude, longitude); 
      new Handler().postDelayed(new Runnable() { 
       @Override 
       public void run() { 
        startActivity(new Intent(SplashScreen.this, MainActivity.class)); 
        finish(); 

       } 
      }, 4000); 


     } else { 
      new Handler().postDelayed(new Runnable() { 
       @Override 
       public void run() { 
        startActivity(new Intent(SplashScreen.this, MainActivity.class)); 
        finish(); 

       } 
      }, 4000); 
     } 
    } 

    private void getCities(double lat, double lng) { 
     Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 
     List<Address> addresses = null; 
     try { 
      addresses = geocoder.getFromLocation(lat, lng, 1); 
      String cityName = addresses.get(0).getLocality(); 
      //String locality = addresses.get(0).getSubLocality(); 
      API.OnCityID(SplashScreen.this, cityName); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 

    /** 
    * Creating google api client object 
    */ 
    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API).build(); 
    } 

    /** 
    * Method to verify google play services on the device 
    */ 
    private boolean checkPlayServices() { 
     int resultCode = GooglePlayServicesUtil 
       .isGooglePlayServicesAvailable(this); 
     if (resultCode != ConnectionResult.SUCCESS) { 
      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { 
       GooglePlayServicesUtil.getErrorDialog(resultCode, this, 
         PLAY_SERVICES_RESOLUTION_REQUEST).show(); 
      } else { 
       Toast.makeText(getApplicationContext(), 
         "This device is not supported.", Toast.LENGTH_LONG) 
         .show(); 
       finish(); 
      } 
      return false; 
     } 
     return true; 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     if (mGoogleApiClient != null) { 
      mGoogleApiClient.connect(); 
     } 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 

     checkPlayServices(); 
    } 

    /** 
    * Google api callback methods 
    */ 
    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " 
       + result.getErrorCode()); 
    } 

    @Override 
    public void onConnected(Bundle arg0) { 

     // Once connected with google api, get the location 
     displayLocation(); 
    } 

    @Override 
    public void onConnectionSuspended(int arg0) { 
     mGoogleApiClient.connect(); 
    } 

    private void CheckGPS() { 
     // Get Location Manager and check for GPS & Network location services 
     LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE); 
     if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) || 
       !lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 
      // Build the alert dialog 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setTitle("Location Services Not Active"); 
      builder.setMessage("Please enable Location Services and GPS"); 
      builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialogInterface, int i) { 
        // Show location settings when the user acknowledges the alert dialog 
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        startActivity(intent); 
        finish(); 

       } 
      }); 
      builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialogInterface, int i) { 
        // Show location settings when the user acknowledges the alert dialog 
        dialogInterface.dismiss(); 
        new Handler().postDelayed(new Runnable() { 
         @Override 
         public void run() { 
          startActivity(new Intent(SplashScreen.this, MainActivity.class)); 
          finish(); 

         } 
        }, 1500); 

       } 
      }); 
      Dialog alertDialog = builder.create(); 
      alertDialog.setCanceledOnTouchOutside(false); 
      alertDialog.show(); 
     } else { 
      setUpLocation(); 
     } 
    } 
} 
+0

如果您使用的是Android Studio,那麼您需要添加Google Play服務的依賴關係 –