2015-05-05 20 views
6
adresinden

ulaşılamıyor. Galaxy Note 2 dışında çoğu cihazda çalışıyor. Google Client'a bağlanıyor, ancak LocationListener'u uygulayan onLocationChanged()'a ulaşamıyor. Herkesin neden kaynaklandığını ve neden sadece bu cihazda olduğunu biliyor musunuz?Samsung Not 2, onLocationChanged()

@Override 
public void onLocationChanged(Location location) { 

    mLastLocation = location; 

    if (mLastLocation != null) { 
     lat = mLastLocation.getLatitude(); 
     lng = mLastLocation.getLongitude(); 

     Toast.makeText(getApplicationContext(), String.valueOf(lat) + "/" + String.valueOf(lng), Toast.LENGTH_LONG).show(); 

     serverUrl = "http://(my server)/offers?lat=" + String.valueOf(mLastLocation.getLatitude()) 
          + "&lng=" + String.valueOf(mLastLocation.getLongitude()) + "&distance=1"; 
     // save 
     makeTag(serverUrl); 

     // after getting location data - unregister listener 
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mFusedLocationCallback); 
     new GetBackgroundUpdate().execute(); 
    } else { 
     // get data from server and update GridView 
     new GetBackgroundUpdate().execute(); 
     Toast.makeText(getApplicationContext(), R.string.no_location_detected, Toast.LENGTH_LONG).show(); 

    } 
/** 
Location methods 
*/ 
protected synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
} 

/** 
* Runs when a GoogleApiClient object successfully connects. 
*/ 
@Override 
public void onConnected(Bundle connectionHint) { 
    // Provides a simple way of getting a device's location and is well suited for 
    // applications that do not require a fine-grained location and that do not need location 
    // updates. Gets the best and most recent location currently available, which may be null 
    // in rare cases when a location is not available. 
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(1000); 
    mLocationRequest.setFastestInterval(500); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback); 

} 

@Override 
public void onConnectionFailed(ConnectionResult result) { 
    // Refer to the javadoc for ConnectionResult to see what error codes might be returned in 
    // onConnectionFailed. 
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); 

    if (mResolvingError) { 
     // Already attempting to resolve an error. 
     return; 
    } else if (result.hasResolution()) { 
     try { 
      mResolvingError = true; 
      result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR); 
     } catch (IntentSender.SendIntentException e) { 
      // There was an error with the resolution intent. Try again. 
      mGoogleApiClient.connect(); 
     } 
    } else { 
     // Show dialog using GooglePlayServicesUtil.getErrorDialog() 
     final AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage(String.valueOf(result.getErrorCode())) 
        .setCancelable(false) 
        .setNegativeButton("Ok", new DialogInterface.OnClickListener() { 
         public void onClick(final DialogInterface dialog, final int id) { 
          dialog.cancel(); 
         } 
        }); 
     final AlertDialog alert = builder.create(); 
     alert.show(); 
     mResolvingError = true; 
    } 

    //new GetBackgroundUpdate().execute(); 
} 

@Override 
public void onConnectionSuspended(int cause) { 
    // The connection to Google Play services was lost for some reason. We call connect() to 
    // attempt to re-establish the connection. 
    Log.i(TAG, "Connection suspended"); 
    mGoogleApiClient.connect(); 
} 

@Override 
protected void onStart() { 
    super.onStart(); 
    mGoogleApiClient.connect(); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    if (mGoogleApiClient.isConnected()) { 
     mGoogleApiClient.disconnect(); 
    } 
} 
+2

Eğer LogCat hattı DistanceFilter.java hiçbir 90 ne – Lal

+0

sonrası misiniz? – Lal

+0

address = server + String.valueOf (mLastLocation.getLatitude()) + "& lng =" + String.valueOf (mLastLocation.getLongitude()) + "& distance =" + mesafe; –

cevap

5

Düzenleme: NullPointerException oluyor Yorumunuzdaki satırından sadece mLastLocation boş olmadığından emin olun.

if (mLastLocation != null){ 
    address = server + String.valueOf(mLastLocation.getLatitude()) + "&lng=" + String.valueOf(mLastLocation.getLongitude()) + "&distance=" + distance; 
} 

Unutulmaması gereken başka bir şey, her zaman mGoogleApiClient geçersiz ve kullanmadan önce bağlı olmadığından emin gerektiğidir.

if (mGoogleApiClient != null && mGoogleApiClient.isConnected()){ 
    //..... use mGoogleApiClient..... 
} 

See documentation here

Ayrıca cihaz ile uygulamanızı derlemek sürümü altındadır Google bazen, Hizmetler mevcuttur mevcut versiyonu oyna olmadığını görmek için bir onay eklemek gerekir. Durum buysa, gösterebileceğiniz bir iletişim kutusu var.

Google Play Hizmetlerinin kullanılabilir olup olmadığını nasıl kontrol edeceğiniz aşağıda açıklanmıştır. getLastLocation(), bu yüzden iyi bir yaklaşım getLastLocation() ilk çağrısından null değeri alırsanız bir konum dinleyici kayıt boş olurdu dönmek için yüksek bir eğilime sahip olması

private boolean isGooglePlayServicesAvailable() { 
     int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
     if (ConnectionResult.SUCCESS == status) { 
      return true; 
     } else { 
      GooglePlayServicesUtil.getErrorDialog(status, this, 0).show(); 
      return false; 
     } 
    } 

Not. Yaratmak bir dinleyici

:

LocationCallback mFusedLocationCallback = new LocationCallback(); 

Sınıf tanımı:

private class LocationCallback implements LocationListener { 

     public LocationCallback() { 

     } 

     @Override 
     public void onLocationChanged(Location location) { 

       mLastLocation = location; 
       lat = String.valueOf(mLastLocation.getLatitude()); 
       lng = String.valueOf(mLastLocation.getLongitude()); 


      } 
    }; 

Sonra sadece kayıt İşte

LocationClient getLastLocation() return null bir LocationListener kayıt için nasıl bir kılavuzdur:
Bu yayını bakın LocationListener:

mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(minTime); 
    mLocationRequest.setFastestInterval(fastestTime); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
    mLocationRequest.setSmallestDisplacement(distanceThreshold); 

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback); 

Düzenleme:

/** 
* Runs when a GoogleApiClient object successfully connects. 
*/ 
@Override 
public void onConnected(Bundle connectionHint) { 
    // Provides a simple way of getting a device's location and is well suited for 
    // applications that do not require a fine-grained location and that do not need location 
    // updates. Gets the best and most recent location currently available, which may be null 
    // in rare cases when a location is not available. 
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    if (mLastLocation != null) { 
     lat = String.valueOf(mLastLocation.getLatitude()); 
     lng = String.valueOf(mLastLocation.getLongitude()); 
    } else { 
     Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show(); 
    } 


    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(1000); 
    mLocationRequest.setFastestInterval(500); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback); 
} 

Belgeleme: for requestLocationUpdates.... ve LocationRequest Sen konum geri aramalar için kayıt önce bağlanacak API için beklemesi gereken, bu gibi bir şey olmalıdır.

Son bir şey, sen application etiketi içinde AndroidManifest.xml bu olduğundan emin olun:

<meta-data 
    android:name="com.google.android.gms.version" 
    android:value="@integer/google_play_services_version" /> 
+0

Kullanmalı mıyım? (MGoogleApiClient! = Null && mGoogleApiClient.isConnected() && mLastLocation! = Null)?Her şeyi bir kerede kontrol eder –

+0

@ jeand'arme Sadece yaptığınız şeye bağlıdır. Bu satırın üçünü de bir kerede kontrol etmek istemezsiniz: 'mLastLocation = LocationServices.FusedLocationApi.getLastLocation (mGoogleApiClient);' getLastLocation() 'nın null olarak geri dönme eğiliminde olduğunu unutmayın, bu nedenle daha iyi bir yaklaşım kayıt olmaktır Boş bir değer alırsanız bir konum dinleyici. Bu yayına bakın: http://stackoverflow.com/questions/16830047/locationclient-getlastlocation-return-null –

+0

Uygulamam tam konuma bağlı olduğu için konum dinleyiciyi kullanmayı deneyeceğim. –