2017-01-18 3 views
0

GoogleApiClientでユーザーの場所を取得しようとしていますが、アクティビティの開始時にGPSが有効になっていれば正常に動作しますが、有効になっていないと、 GPS、私は場所を取得するように見えることはできません。 LocationListenerを使用しようとしています。ネイティブとGooglePlayServicesの両方のリスナーを試しました。 GPSがのonCreateで有効になっている場合ロケーションを取得できません。

チェック:ここに私のコードがある

//Ask the user to enable GPS if it is not. 
    mLocationRequestBalancedPowerAccuracy = new LocationRequest() 
      .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY) 
      .setInterval(3600000) 
      .setFastestInterval(300000); 
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
      .addLocationRequest(mLocationRequestBalancedPowerAccuracy); 
    PendingResult<LocationSettingsResult> result = 
      LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
     @Override 
     public void onResult(@NonNull LocationSettingsResult result) { 
      final Status status = result.getStatus(); 
      //final LocationSettingsStates states = result.getLocationSettingsStates(); 
      switch (status.getStatusCode()) { 
       case LocationSettingsStatusCodes.SUCCESS: 
        break; 
       case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
        try { 
         status.startResolutionForResult(
           MainActivity.this, 
           REQUEST_CHECK_SETTINGS); 
        } catch (IntentSender.SendIntentException e) { 
         Log.d("Location error", e.toString()); 
        } 
        break; 
       case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 

        break; 
      } 
     } 
    }); 

結果は解決する必要がある場合、ユーザーがGPSを有効にするために受け入れた場合、私は場所のためのリスニングを開始はonResultメソッドを実行します。

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    //final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); 
    switch (requestCode) { 
     case REQUEST_CHECK_SETTINGS: 
      switch (resultCode) { 
       case Activity.RESULT_OK: 
        // All required changes were successfully made 
        // User accepted to use GPS, start searching for location 

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
         return; 
        } 
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequestBalancedPowerAccuracy, this); 
        Log.d("locationmanager", "location result ok"); 
        break; 
       case Activity.RESULT_CANCELED: 
        // The user was asked to change settings, but chose not to 
        this.finishAffinity(); 
        break; 
       default: 
        break; 
      } 
      break; 
    } 
} 

行Log.d( "locationmanager"、 "location result ok");上記の行は実行されていないようです。

@Override 
public void onLocationChanged(Location location) { 
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
    Log.d("changed location", String.valueOf(location.getLatitude()) + " " + String.valueOf(location.getLongitude())); 
} 
+0

onConnected()関数でロケーションリクエストを行います。 – Shuddh

+0

私はすでにそれをやっていますが、起動時にその場所が利用できない場合、onConnectedの場所はnullになります。 –

答えて

0

この場所リスナークラスを使用してみてください:あなたの活動に

/** 
* Getting Navigation Updates. 
* <p> 
* Demonstrates how to use the Fused Navigation Provider API to get updates about a device's 
* location. The Fused Navigation Provider is part of the Google Play services location APIs. 
* <p> 
* 
* Author Mayank 
*/ 
public class GPSLocationListener implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener { 

    protected static final String TAG = "location-updates-sample"; 

    /** 
    * The desired interval for location updates. Inexact. Updates may be more or less frequent. 
    */ 
    public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; 

    /** 
    * The fastest rate for active location updates. Exact. Updates will never be more frequent 
    * than this value. 
    */ 
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 
      UPDATE_INTERVAL_IN_MILLISECONDS/2; 

    /** 
    * Provides the entry point to Google Play services. 
    */ 
    protected GoogleApiClient mGoogleApiClient; 

    /** 
    * Stores parameters for requests to the FusedLocationProviderApi. 
    */ 
    protected LocationRequest mLocationRequest; 

    /** 
    * Represents a geographical location. 
    */ 
    protected Location mCurrentLocation; 

    private Activity mActivity; 


    public GPSLocationListener(Activity activity) { 

     this.mActivity = activity; 

     // Kick off the process of building a GoogleApiClient and requesting the LocationServices API. 
     buildGoogleApiClient(); 

    } 

    /** 
    * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the 
    * LocationServices API. 
    */ 
    protected synchronized void buildGoogleApiClient() { 
     Log.i(TAG, "Building GoogleApiClient"); 
     mGoogleApiClient = new GoogleApiClient.Builder(mActivity) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     createLocationRequest(); 
    } 

    /** 
    * Sets up the location request. Android has two location request settings: 
    * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control 
    * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in 
    * the AndroidManifest.xml. 
    * <p/> 
    * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update 
    * interval (5 seconds), the Fused Navigation Provider API returns location updates that are 
    * accurate to within a few feet. 
    * <p/> 
    * These settings are appropriate for mapping applications that show real-time location 
    * updates. 
    */ 
    protected void createLocationRequest() { 
     mLocationRequest = new LocationRequest(); 

     // Sets the desired interval for active location updates. This interval is 
     // inexact. You may not receive updates at all if no location sources are available, or 
     // you may receive them slower than requested. You may also receive updates faster than 
     // requested if other applications are requesting location at a faster interval. 
     mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 

     // Sets the fastest rate for active location updates. This interval is exact, and your 
     // application will never receive updates faster than this value. 
     mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 

     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    } 

    /** 
    * Requests location updates from the FusedLocationApi. 
    */ 
    protected void startLocationUpdates() { 
     // The final argument to {@code requestLocationUpdates()} is a LocationListener 
     // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html). 
     LocationServices.FusedLocationApi.requestLocationUpdates(
       mGoogleApiClient, mLocationRequest, this); 
    } 

    /** 
    * Removes location updates from the FusedLocationApi. 
    */ 
    protected void stopLocationUpdates() { 
     // It is a good practice to remove location requests when the activity is in a paused or 
     // stopped state. Doing so helps battery performance and is especially 
     // recommended in applications that request frequent location updates. 

     // The final argument to {@code requestLocationUpdates()} is a LocationListener 
     // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html). 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
    } 

    public void onStart() { 
     mGoogleApiClient.connect(); 

     // Within {@code onPause()}, we pause location updates, but leave the 
     // connection to GoogleApiClient intact. Here, we resume receiving 
     // location updates if the user has requested them. 

    } 

    public void onStop() { 

     // Stop location updates to save battery, but don't disconnect the GoogleApiClient object. 
     if (mGoogleApiClient.isConnected()) { 
      stopLocationUpdates(); 
      mGoogleApiClient.disconnect(); 
     } 

    } 

    /** 
    * Runs when a GoogleApiClient object successfully connects. 
    */ 
    @Override 
    public void onConnected(Bundle connectionHint) { 
     Log.i(TAG, "Connected to GoogleApiClient"); 

     // If the initial location was never previously requested, we use 
     // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store 
     // its value in the Bundle and check for it in onCreate(). 
     if (mCurrentLocation == null) { 
      mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
      locationReceived(); 
     } 

     // start location updates. 
     startLocationUpdates(); 
    } 

    /** 
    * Callback that fires when the location changes. 
    */ 
    @Override 
    public void onLocationChanged(Location location) { 
     mCurrentLocation = location; 
    } 

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

    public GoogleApiClient getGoogleApiClient(){ 
     return mGoogleApiClient; 
    } 

} 

:これはあなたを助け

//provides gps location updates 
     private GPSLocationListener gpsLocationListener; 

    @Override 
    public void onStart() { 
     super.onStart(); 
     //call to location listener to start location updates when activity gets started 
     if (gpsLocationListener != null) { 
      gpsLocationListener.onStart(); 
     } 

     } 
     @Override 
     public void onStop() { 
      super.onStop(); 
      //call to stop location updates when activity gets stopped 
      if (gpsLocationListener != null) { 
       gpsLocationListener.onStop(); 
      } 

     } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     //call to initialize gpsLocationLister instance 
     gpsLocationListener = new GPSLocationListener((MainActivity) mainView); 

    } 

希望

は、最後にここに私のリスナーです。

関連する問題