Не удается подключиться к клиенту GoogleAPI, нет подключения, нет сбоя

Таким образом , я пытаюсь подключиться кGoogle API client, но я не получаю ответ от моего onConnectedметода или onConnectionFailedметода. Оба метода подобны so, соответственно:

 public void onConnected(@Nullable Bundle bundle) {

    Log.d(TAG, "OnConnected");

    if (PackageManager.PERMISSION_GRANTED ==
            (ContextCompat.checkSelfPermission(mParentBase, android.Manifest.permission.ACCESS_FINE_LOCATION)))

    {
        Log.d(TAG, "Permission Was Granted" );
        mMyLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (mMyLocation == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, requestLocation, mParentIntent);
        } else {
            Log.d(TAG, mMyLocation.toString());
        }
    } else {
        ActivityCompat.requestPermissions(mParentActivity, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_ACCESS_FINE_LOCATION);
        Log.d(TAG, "Permission Was Requested" );
    }

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    Log.i(TAG, "Connection Failed");

    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(mParentActivity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    } else {
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }

}

У меня есть открытый интерфейс, который запускает соединение с API:

public void connect()
    {
        mGoogleApiClient.connect();
        Log.d(TAG, "Connection Requested");
    }

Я могу видеть приведенный выше файл журнала на консоли запуска Android Studio .

Кто-нибудь еще видел этот тип проблемы?

Редактировать:
Код для построения и инициализации клиента

public myLocation(Context Base, Activity activitiyBase, PendingIntent intent) {
        mParentBase = Base;
        mParentActivity = activitiyBase;
        mParentIntent = intent;
        initialLocationService();
    }

    /**
     *  Initialize the Location Service and API Client
     */

    private void initialLocationService(){
         mGoogleApiClient = new GoogleApiClient.Builder(mParentBase)
             .addConnectionCallbacks(this)
             .addOnConnectionFailedListener(this)
             .addApi(LocationServices.API)
             .build();

         requestLocation = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10*1000)
            .setFastestInterval(1*1000);

класс реализует следующее:

public class myLocation implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        ActivityCompat.OnRequestPermissionsResultCallback,
        LocationListener
{

1 ответ

  1. ОК. Я собрал код, который, надеюсь, поможет вам найти вашу проблему. У меня есть этот код в качестве рабочего приложения на устройстве. Я использовал смесь вашего кода с моим. Сравнивая различия, вы сможете сузить круг проблем. 1-й класс myLocation…

    public class myLocation implements
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            ActivityCompat.OnRequestPermissionsResultCallback,
            LocationListener {
    
        private final static String TAG = "myLocation";
        private final static int MY_PERMISSION_ACCESS_FINE_LOCATION = 1;
        private final static long ONE_SECOND = 1000;
        private final static long UPDATE_INTERVAL = ONE_SECOND;
        private final static long FASTEST_UPDATE_INTERVAL = ONE_SECOND;
    
        private GoogleApiClient mGoogleApiClient = null;
        Context mParentBase;
        Activity mParentActivity;
    
        public myLocation(Context Base, Activity activitiyBase) {
            mParentBase = Base;
            mParentActivity = activitiyBase;
            initialLocationService();
        }
    
        // you call this an interface in your question but I'm just
        //     making it a public method which can be called from Activity
        public void connect()
        {
            mGoogleApiClient.connect();
            Log.d(TAG, "Connection Requested");
        }
    
        @Override
        public void onConnected(@Nullable Bundle bundle) {
    
            Log.d(TAG, "OnConnected");
    
            if (PackageManager.PERMISSION_GRANTED ==
                    (ContextCompat.checkSelfPermission(mParentBase,
                    android.Manifest.permission.ACCESS_FINE_LOCATION)))
    
            {
                Log.d(TAG, "Permission Was Granted");
                startLocationUpdates();
            } else {
                ActivityCompat.requestPermissions(mParentActivity,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSION_ACCESS_FINE_LOCATION);
                Log.d(TAG, "Permission Was Requested");
            }
        }
    
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
            Log.i(TAG, "Connection Failed");
            // just logging for now
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, 
                @NonNull String[] permissions, @NonNull int[] grantResults) {
            // loading from Android Studio, not going to worry about this now
        }
    
        @Override
        public void onConnectionSuspended(int i) {
            Log.i(TAG, "Connection Suspended");
            // just logging for now, not trying to resolve failure
        }
    
        @Override
        public void onLocationChanged(Location location) {
            Log.i(TAG, "Entered the onLocationChanged() method");
            // this calls one or the other private methods that don't
            //    matter to your problem.  I can post them if you like.
            if (location != null) {
                showLocationInfo(location);
            } else {
                Log.d(TAG, "Can't get last location");
                setAllUnavailable();
            }
        }
    
        private void initialLocationService() {
            if (mGoogleApiClient == null) {
                mGoogleApiClient = new GoogleApiClient.Builder(mParentBase)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .addApi(LocationServices.API)
                        .build();
            }
        }
    
        private void locationRequestUpdates(long interval, long fastestInterval, int priority) {
            // remove any previous updates
            try {
                if(mGoogleApiClient.isConnected()) {
                    LocationServices.FusedLocationApi
                   .removeLocationUpdates(mGoogleApiClient, this);
                }
            } catch (SecurityException e) {
                logException("SecurityException", e);
            }
    
            // build a new request
            LocationRequest locationRequest = new LocationRequest()
                    .setInterval(interval)
                    .setFastestInterval(fastestInterval)
                    .setPriority(priority);
    
            // now send new request
            try {
                if(mGoogleApiClient.isConnected()) {
                    LocationServices.FusedLocationApi.requestLocationUpdates(
                            mGoogleApiClient, locationRequest, this);
                }
            } catch (SecurityException e) {
                logException("SecurityException", e);
            }
        }
    
        private void startLocationUpdates() {
            Location lastLocation = null;
            try {
                lastLocation = LocationServices.FusedLocationApi.getLastLocation(
                        mGoogleApiClient);
            } catch (SecurityException e) {
                logException("SecurityException", e);
            }
    
            if (lastLocation != null) {
                showLocationInfo(lastLocation);
            } else {
                Log.d(TAG, "Can't get last location");
                setAllUnavailable();
            }
    
            locationRequestUpdates(UPDATE_INTERVAL,
                    FASTEST_UPDATE_INTERVAL,
                    LocationRequest.PRIORITY_HIGH_ACCURACY);
        }
    }    
    

    В деятельности, в onCreate()

    mMyLocation = new myLocation(getApplicationContext(), this);
    

    и в onStart()

    mMyLocation.connect();
    

    Надеюсь, это поможет.