2015-10-01 2 views
0

Приветствия дня. Я работаю над приложением, в котором мне нужно показать карту. Я хочу, чтобы карта отображалась по умолчанию в моем текущем местоположении, но я не могу этого сделать. Я пробовал несколько способов получить текущее местоположение (LatLng). Я тоже следил за этим link, ссылка отлично работает на эмуляторе, когда я отправляю LatLng из Android Device Monitor, но не работает на реальном устройстве.Невозможно получить текущее местоположение в 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

Вы должны обработать случай, когда местоположение является нулевым, и вернуться к разумному умолчанию, например, центрировать карту в главном городе. В документации Google указано, что местоположение 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, то вам нужно добавить зависимости сервисов Google Play –

Смежные вопросы