2016-04-04 9 views
2

Hier ist mein Code, der die gleiche Methode verwendet - einmal während onCreate() in meinem MainActivity und einmal nach dem Benutzer auf eine Schaltfläche klicktLocationServices.FusedLocationApi.getLastLocation nicht in onCreate Arbeits() -Methode

// Below code not working during onCreate 
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 

    // Create an instance of GoogleAPIClient. From Google API demo code 
    if (mGoogleApiClient == null) { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 

    startLocationOnScreen.setText(getCurrentLocationViaPhoneLocation()); 

// Surprisingly same method works if it's called after a button press! 

     startButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

          startLocationOnScreen.setText(getCurrentLocationViaPhoneLocation()); 

Warum wäre dies ? Ich möchte grundsätzlich den aktuellen Standort des Benutzers abrufen, wenn die App geladen wird, und nicht den Benutzer zwingen, eine Taste zu drücken, um die gleiche Adresse zu erhalten.

Implementierung von getCurrentLocationViaPhoneLocation() Methode - (meist von Google-API-Dokumentation entnommen)

protected String getCurrentLocationViaPhoneLocation() { 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return "Error - location services not available!"; 
    } 
    startLocation = LocationServices.FusedLocationApi.getLastLocation(
      mGoogleApiClient); 
    if (startLocation != null) { 
     Log.e("We are at ", String.valueOf(startLocation.getLatitude())); 
     Log.e("We are at ", String.valueOf(startLocation.getLongitude())); 

     Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 

     try { 
      List<Address> addressList = geocoder.getFromLocation(startLocation.getLatitude(), startLocation.getLongitude(), 1); 

      if (addressList != null && addressList.size() > 0) { 


       currentCity = addressList.get(0).getLocality(); 


       Address address = addressList.get(0); 
       StringBuilder sb = new StringBuilder(); 
       for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { 
        sb.append(address.getAddressLine(i)).append("\n"); 
       } 

       return (sb.toString()); 

      } 

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


    } 

    return ("Error - current location unavailable!"); 
} 

Edit: ich: Error - current location unavailable! während onCreate() was bedeutet, dass startLocation==null, wenn das Verfahren bei onCreate() aufgerufen wird.

Antwort

1

Ich vermute, der GoogleApiClient ist noch nicht verbunden, wenn Sie die Methode zum ersten Mal aufrufen (d. H. Während onCreate).

Sie rufen bereits die addConnectionCallbacks Methode des Builders. Daher sollten Sie in Ihrer Aktivität die onConnected(Bundle) Methode von GoogleApiClient.ConnectionCallbacks implementiert haben. Rufen Sie die Methode getCurrentLocationViaPhoneLocation hier anstatt in der onCreated auf, dann können Sie sicher sein, dass der GoogleApiClient richtig verbunden ist.

Wenn die Methode onConnected nicht aufgerufen wird, versuchen Sie, mGoogleApiClient.connect() nach dem Erstellen der Instanz in Ihrem onCreate hinzuzufügen.

Ich hoffe, dass hilft!

+0

Ehrfürchtig, das war das Problem, den Aufruf getCurrentLocationViaPhoneLocation in der OnConnected (Bundle) -Methode das Problem zu lösen. Ich danke dir sehr! – zooter

+0

Gern geschehen. Ich bin froh, dass es geklappt hat! – Phoca