简体   繁体   English

Google+登录在Android片段上无法正常使用

[英]Google+ Login Not working properly on Android fragment

I am working with google+ login to my application and when i done it using a activity its work charm and after that i move my code into a fragment and after that when i try to login to google+ its not working i have to open the fragment activity 2 times to login to the google+ can anyone tell me what happen the code to the fragment is added below 我正在使用谷歌+登录到我的应用程序,当我使用活动完成它的工作魅力,然后我将我的代码移动到一个片段,然后当我尝试登录到谷歌+它不工作我必须打开片段活动2次登录谷歌+任何人都可以告诉我,下面添加了片段的代码发生了什么

public class GooglePluseFragment extends Fragment implements
        ConnectionCallbacks, OnConnectionFailedListener {

private static final int RC_SIGN_IN = 0;

private static final String TAG = "MainActivity";

private static final int PROFILE_PIC_SIZE = 800;

private GoogleApiClient mGoogleApiClient;

private boolean mIntentInProgress;

private boolean mSignInClicked;

private ConnectionResult mConnectionResult;

private SignInButton btnSignIn;
private Button btnSignOut;

private Context mContext;
private Activity mActivity;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mActivity = getActivity();
    mContext = getActivity().getApplicationContext();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.compund_google_pluse_fragment,
            container, false);

    btnSignIn = (SignInButton) view.findViewById(R.id.btn_sign_in);
    btnSignOut = (Button) view.findViewById(R.id.btn_sign_out);

    sharedPref = view.getContext().getSharedPreferences(
            Constantz.SHEARED_PREFEREANCE, Context.MODE_PRIVATE);

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

    btnSignIn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            signInWithGplus();

        }
    });

    btnSignOut.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            signOutFromGplus();
        }
    });

    return view;
}

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

@Override
public void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onActivityResult(int requestCode, int responseCode,
        Intent intent) {

    if (requestCode == RC_SIGN_IN) {
        if (responseCode != Activity.RESULT_OK) {
            mSignInClicked = false;
        }

        mIntentInProgress = false;

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

        }
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    if (!result.hasResolution()) {
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
                mActivity, 0).show();
        Log.e(TAG, "" + result.getErrorCode());
        return;
    }

    if (!mIntentInProgress) {

        mConnectionResult = result;

        if (mSignInClicked) {

            Log.e(TAG, "" + result.getErrorCode());
            resolveSignInError();
        }
    }

}

@Override
public void onConnected(Bundle arg0) {
    mSignInClicked = false;

    getProfileInformation();

    updateUI(true);

}

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

}

private void updateUI(boolean isSignedIn) {
    if (isSignedIn) {
        btnSignIn.setVisibility(View.GONE);
        btnSignOut.setVisibility(View.VISIBLE);

    } else {
        btnSignIn.setVisibility(View.VISIBLE);
        btnSignOut.setVisibility(View.GONE);

    }
}

/**
 * Sign-in into google
 * */
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(mActivity,
                    RC_SIGN_IN);
        } catch (SendIntentException e) {
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}

/**
 * Fetching user's information name, email, profile pic
 * */
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 email = Plus.AccountApi.getAccountName(mGoogleApiClient);

            Log.e(TAG, "Name: " + personName + ", plusProfile: "
                    + personGooglePlusProfile + ", email: " + email
                    + ", Image: " + personPhotoUrl + " user id:"
                    + currentPerson.getId());






        } else {
            Toast.makeText(mContext, "Person information is null",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Sign-out from google
 * */
private void signOutFromGplus() {
    if (mGoogleApiClient.isConnected()) {
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();

        updateUI(false);

    }
}

} }

this is how i added framgent in the fragment activity 这就是我在片段活动中添加framgent的方式

pluseFragment = new GooglePluseFragment();

        FragmentManager manager = getSupportFragmentManager();

        FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.pluse_frame_layout, pluseFragment);
transaction.commit();

can somebody tell me what i have done wrong ? 谁能告诉我我做错了什么? why i have to open the activity two times to login thank you 为什么我要打开活动两次才能登录谢谢

Finally found the answer, Problem was when the result activity call in the fragment was catch by the parent activity so you have to manually redirect the result to your fragment. 最后找到答案,问题是当片段中的结果活动调用被父活动捕获时,您必须手动将结果重定向到片段。 Just have to add this line in your Parent Fragment Activity 只需在父片段活动中添加此行

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == GooglePluseFragment.RC_SIGN_IN) {
            GooglePluseFragment fragment = (GooglePluseFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.pluse_frame_layout);
            fragment.onActivityResult(requestCode, resultCode, data);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    } 

Easy Solution for this :: just create the static method in fragment " 简单的解决方案::只需在片段中创建静态方法“

public static myOnActivityResult(int requestCode, int resultCode, Intent data){
.....Enter same code
} 

and

call this method from Parant Activity on 从Parant Activity调用此方法

     protected void onActivityResult(int requestCode, int resultCode, Intent data) {

.....
MyFragment.myOnActivityResult(requestCode,resultCode,data)

}

thats it 而已

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM