Проблемы со входом в гугл плюс на андроиде

Я добавил вход Google Plus в свое приложение. Когда я нажимаю кнопку входа с помощью Google, приложение зависает и перестает отвечать на запросы. когда я закрываю приложение и перезапускаю его, вход происходит без проблем. Что происходит не так? Код ниже. Макет

            <com.google.android.gms.common.SignInButton
                android:id="@+id/sign_in_button"
                android:layout_width="match_parent"
                android:layout_height="55dp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:elevation="10dp"/>

и код Java

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launcher);
         mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_LOGIN).build();

    mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
    mSignInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mGoogleApiClient.isConnecting()) {
                mSignInClicked = true;
                resolveSignInError();
            }
        }
    });
    mSignInButton.setSize(SignInButton.SIZE_WIDE);
}
private void resolveSignInError() {
    if (mConnectionResult.hasResolution()) {
        try {
            mIntentInProgress = true;
            startIntentSenderForResult(mConnectionResult.getResolution()
                    .getIntentSender(), RC_SIGN_IN, null, 0, 0, 0);
        } catch (IntentSender.SendIntentException e) {
            // The intent was canceled before it was sent. Return to the
            // default
            // state and attempt to connect to get an updated
            // ConnectionResult.
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}

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

protected void onStop() {
    super.onStop();

    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    if (!mIntentInProgress) {
        // Store the ConnectionResult so that we can use it later when the
        // user clicks
        // 'sign-in'.
        mConnectionResult = result;

        if (mSignInClicked) {
            // The user has already clicked 'sign-in' so we attempt to
            // resolve all
            // errors until the user is signed in, or they cancel.
            resolveSignInError();
        }
    }
}

@Override
public void onConnected(Bundle arg0) {
    Log.e("Connection","success");   
}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub

}



protected void onActivityResult(int requestCode, int responseCode,
                                Intent intent) {
    if (requestCode == RC_SIGN_IN) {
        if (responseCode != RESULT_OK) {
            mSignInClicked = false;
        }

        mIntentInProgress = false;

        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    }
}

Logcat показал, что код результата равен -1, а намерение равно null в onActivityResult. И снова вызывается mGoogleApi.connect(). приложение просто зависает на этом этапе, и обратные вызовы не запускаются. Что я делаю не так?


person Tchinmai    schedule 02.07.2015    source источник


Ответы (2)


Я использую вот так

private boolean mSignInClicked;
private GoogleApiClient mGoogleApiClient;

mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this).addApi(Plus.API) 
    .addScope(Plus.SCOPE_PLUS_LOGIN).build();

напишите приведенный выше код в onCreate()...

метод onClick кнопки gplus

private void signInWithGplus() {
    if (!mGoogleApiClient.isConnecting()) {
        mSignInClicked = true;
        resolveSignInError();
    }
}

/**
 * Method to resolve any signin errors
 * */
private void resolveSignInError() {
    if (mConnectionResult.hasResolution()) {
        try {
            mIntentInProgress = true;
            mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
        } catch (SendIntentException e) {
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    if (!result.hasResolution()) {
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
                0).show();
        return;
    }

    if (!mIntentInProgress) {
        // Store the ConnectionResult for later usage
        mConnectionResult = result;

        if (mSignInClicked) {
            // The user has already clicked 'sign-in' so we attempt to
            // resolve all
            // errors until the user is signed in, or they cancel.
            resolveSignInError();
        }
    }

}

@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub

    mSignInClicked = false;

    // Get user's information
    getProfileInformation();

}

@Override
public void onConnectionSuspended(int arg0) {
    mGoogleApiClient.connect();
}


private void getProfileInformation() {
    try {
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
            Person currentPerson = Plus.PeopleApi
                    .getCurrentPerson(mGoogleApiClient);
            String personName = currentPerson.getDisplayName();
            String personPhotoUrl = currentPerson.getImage().getUrl();
            String personGooglePlusProfile = currentPerson.getUrl();
            String reg_id = currentPerson.getId();
            String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

            Log.e("Google plus responce", "Name: " + personName + ", plusProfile: "
                    + personGooglePlusProfile + ", email: " + email
                    + ", Image: " + personPhotoUrl+"REG ID " +reg_id );

            personPhotoUrl = personPhotoUrl.substring(0,
                    personPhotoUrl.length() - 2)
                    + PROFILE_PIC_SIZE;
}

В onActivityдля результата

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d("FbLogin", "Result Code is = " + resultCode +"");
    if (requestCode == RC_SIGN_IN) {
        if (resultCode != RESULT_OK) {
            mSignInClicked = false;
        }
        mIntentInProgress = false;
        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    }
}

Пользовательская кнопка

<ImageView
        android:id="@+id/btn_gplus"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="3dp"
        android:layout_weight="1"
        android:background="@drawable/btn_cha_gmail" />

Надеюсь, что это будет работать хорошо для вас .... Программирование Happeee !!!!!!

person Amaresh Jana    schedule 02.07.2015
comment
‹meta-data android:name=com.google.android.gms.version android:value=@integer/google_play_services_version /› добавьте это в свой манифест...... - person Amaresh Jana; 03.07.2015
comment
это проблема с подписанным apk? - person Amaresh Jana; 03.07.2015
comment
если это произойдет после подписания в apk, вам нужно добавить ключ SHA в проект, созданный в консоли Google API.... - person Amaresh Jana; 03.07.2015
comment
это только отладочная сборка. Мой SHA-1 правильный. в манифесте уже есть эти метаданные - person Tchinmai; 03.07.2015

У меня тоже была такая же проблема. В моем onActivityResult была какая-то логическая ошибка. Проверьте свой метод onActivityResult. Только тогда ваша проблема будет решена.

person mayank.miig    schedule 19.10.2015