Google加错误从Android登录

时间:2015-09-08 06:23:16

标签: android google-plus

我正在通过google plus在我的项目中登录。但是我在这里遇到的问题是在点击google plus登录按钮之后。我要求我从设备帐户列表中选择google plus帐户并在之后选择按钮没有任何事情发生。我必须再次按google plus按钮来调用OnConnected()方法。但是我想在选择谷歌帐户后第一次点击按钮时调用OnConnected()。请帮忙。

Here is my code for my complete java class:



    public class LoginFragment extends Fragment implements View.OnClickListener,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    TextView Fpassword, Signup;
    EditText email, password;
    ImageView Signin, fb_button, gplus_button;
    LogInActivity myContext;
    static String personName;
    static int requestcode;
    Validation validation;
    String LOG_TAG="ani";
    ProgressDialog pd;
    ProgressDialog dialog;
    private boolean mIntentInProgress;
    FragmentManager fragmentManager;
    private CallbackManager callbackmanager;
    //for G+
    private static final int PROFILE_PIC_SIZE = 50;
    static GoogleApiClient mGoogleApiClient;
    private ConnectionResult mConnectionResult;
    private boolean mSignInClicked;
    static final int RC_SIGN_IN = 0;
    /* Is there a ConnectionResult resolution in progress? */
    private boolean mIsResolving = false;
    private RequestQueue mQueue;
    /* Should we automatically resolve ConnectionResults when possible? */
    private boolean mShouldResolve = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(Plus.API).addScope(new Scope(Scopes.PROFILE)).build();
        callbackmanager = CallbackManager.Factory.create();

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        myContext = (LogInActivity) activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        Fpassword = (TextView) view.findViewById(R.id.ForgotPassword);
        Signup = (TextView) view.findViewById(R.id.SignUp);
        email = (EditText) view.findViewById(R.id.Email_Val);
        password = (EditText) view.findViewById(R.id.PasswordVal);
        Signin = (ImageView) view.findViewById(R.id.signin);
        fb_button = (ImageView) view.findViewById(R.id.FB_btn);
        //facebook and google connection manager initialisation..
        gplus_button = (ImageView) view.findViewById(R.id.Gplus_btn);
        FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
        Fpassword.setPaintFlags(Fpassword.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        Signup.setPaintFlags(Signup.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        email.setHintTextColor(Color.parseColor("#727272"));
        password.setHintTextColor(Color.parseColor("#727272"));
        Fpassword.setOnClickListener(this);
        Signup.setOnClickListener(this);
        Signin.setOnClickListener(this);
        fb_button.setOnClickListener(this);
        gplus_button.setOnClickListener(this);
        validation = new Validation();
        return view;

    }

    @Override
    public void onClick(View v)
    {
        if (v.getId() == R.id.ForgotPassword)
        {
            Fragment forgotpassword = new ForgotPasswordFragment();
            myContext.getSupportFragmentManager().beginTransaction().add(R.id.container_login, forgotpassword).addToBackStack("fragBack1").commit();

        }
        else if (v.getId() == R.id.SignUp)
        {
            Fragment signup = new SignUpFragment();
            myContext.getSupportFragmentManager().beginTransaction().add(R.id.container_login, signup).addToBackStack("fragBack1").commit();

        }

        else if (v.getId() == R.id.signin)
        {


            if (!validation.isValidEmail(email.getText().toString())) {

                email.setError("please enter a Valid Email Address");
            }

            if (!validation.isValidPassword(password.getText().toString())) {

                password.setError("min password length has to be 6");
            }

            if (validation.isValidEmail(email.getText().toString()) && validation.isValidPassword(password.getText().toString()))
            {
                if (Network.isNetworkAvailable(myContext))
                {
                    signInVolley();
                }
                else
                {
                    Toast.makeText(myContext, "no internet connection", Toast.LENGTH_SHORT).show();
                }

            }
        }
        else if (v.getId() == R.id.FB_btn)
        {
            if (Network.isNetworkAvailable(myContext))
            {//Intent intent_signin = new Intent(myContext, HomeActivity.class);
                // startActivity(intent_signin);
                Fblogin();
            }
            else
            {
                Toast.makeText(myContext,"no internet connection",Toast.LENGTH_SHORT).show();
            }

        } else if (v.getId() == R.id.Gplus_btn)
        {

            if(Network.isNetworkAvailable(myContext)) {
                //Intent intent_signin = new Intent(myContext, HomeActivity.class);
                // startActivity(intent_signin);
                onSignInClicked();
                Log.d("ajflow","onclick");

            }
            else
            {
                Toast.makeText(myContext,"no internet connection",Toast.LENGTH_SHORT).show();
            }


        }

    }

    private void onSignInClicked() {
        // User clicked the sign-in button, so begin the sign-in process and automatically
        // attempt to resolve any errors that occur.

        mShouldResolve = true;
        mGoogleApiClient.connect();
        Log.d("ajflow", "onsignin click");


    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d("ajflow", "onStart");


    }

    @Override
    public void onStop() {
        super.onStop();

    }
    private void Fblogin()
    {


        // Set permissions
        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile, email, user_birthday,user_friends"));

        LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                // Application code
                                Log.d("LoginActivity", response.toString());
                                Log.d("LoginActivity", object.toString());
                                String jsonresult = String.valueOf(object);
                                System.out.println("JSON Result" + jsonresult);
                                String str_firstname = null, str_id = null;
                                String responseValue = response.toString();
                                responseValue = responseValue.replace("Response:  responseCode: 200,", "");
                                Log.d("animeshnew", responseValue);


                                try {
                                    str_firstname = object.getString("name");
                                    str_id = object.getString("id");
                                    String str_email = object.getString("email");
                                    Intent login = new Intent(myContext, HomeActivity.class);
                                    String urlValue = "https://graph.facebook.com/" + str_id + "/picture?width=" + PROFILE_PIC_SIZE + "&height=" + PROFILE_PIC_SIZE;

                                    SharedPref.Create_SharePref(myContext, str_firstname, urlValue);
                                    LoginManager.getInstance().logOut();
                                    startActivity(login);
                                    myContext.finish();


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Log.d("animesh123", "aa");
                                }


                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender, birthday,picture");
                request.setParameters(parameters);
                request.executeAsync();


            }

            @Override
            public void onCancel() {
                // App code
                Log.v("LoginActivity", "cancel");
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                Log.v("LoginActivity", exception.getCause().toString());
                Toast.makeText(myContext, exception.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    //to check if the fb user is logged in or not
    public static boolean isLoggedIn() {
        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        return accessToken != null;
    }



    @Override
    public void onConnected(Bundle bundle)
    {
        Log.d("ajflow","onconnected");
        getProfileInfo();


    }
    public void getProfileInfo()
    {
        mSignInClicked = false;
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null)
        {
            Log.d("ajflow", "profileinfo");
            Toast.makeText(myContext, "User is connected!", Toast.LENGTH_LONG).show();
            Person currentPerson = Plus.PeopleApi
                    .getCurrentPerson(mGoogleApiClient);
            personName = currentPerson.getDisplayName();
            String id=currentPerson.getId();
            String birthDate=currentPerson.getAboutMe();
            String personPhotoUrl = currentPerson.getImage().getUrl();
            String personGooglePlusProfile = currentPerson.getUrl();
            String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

            Log.d("sachin", "Name: " + personName + " " + currentPerson.getName() + ", plusProfile: "
                    + personGooglePlusProfile + ", email: " + email
                    + ",BirthDay:" + birthDate + ",Id :"+id+", Image: " + personPhotoUrl);
            personPhotoUrl = personPhotoUrl.substring(0,
                    personPhotoUrl.length() - 2)
                    + PROFILE_PIC_SIZE;

            Intent login=new Intent(myContext,HomeActivity.class);
            SharedPref.Create_SharePref(myContext,personName, personPhotoUrl);
            signOutFromGplus();
            startActivity(login);
            myContext.finish();


        }
        else
        {
            Toast.makeText(myContext,"Problem in connection",Toast.LENGTH_SHORT);
        }
    }

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





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

        super.onActivityResult(requestCode, resultCode, data);
        if(callbackmanager!=null){
            callbackmanager.onActivityResult(requestCode,resultCode,data);
        }
        Log.d("ani", "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
        Log.d("ajflow","onactivityresult");

          if (requestCode == RC_SIGN_IN) {
            // If the error resolution was not successful we should not resolve further.
            if (resultCode != getActivity().RESULT_OK) {
                mShouldResolve = false;
            }

            mIsResolving = false;
            mGoogleApiClient.connect();
        }

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult)
    {
        Log.d("ajflow","onconnectionfailed");
        // Could not connect to Google Play Services.  The user needs to select an account,
        // grant permissions or resolve an error in order to sign in. Refer to the javadoc for
        // ConnectionResult to see possible error codes.
        Log.d("ani", "onConnectionFailed:" + connectionResult);

        if (!mIsResolving && mShouldResolve)
        {
            Log.d("ajflow","both false true");
            if (connectionResult.hasResolution()) {
                mSignInClicked = false;
                try {
                        Log.d("ajflow","has resolution");

                    connectionResult.startResolutionForResult(getActivity(), RC_SIGN_IN);
                    Log.d("ajflow", "try over");
                    mIsResolving = true;
                } catch (IntentSender.SendIntentException e) {
                    Log.e("ani", "Could not resolve ConnectionResult.", e);
                    mIsResolving = false;
                    Log.d("ajflow","in catch");

                    mGoogleApiClient.connect();

                }
            }
        }


    }
    /**
     * Sign-out from google
     * */
    static void signOutFromGplus() {
        Log.d("ajflow","signout");
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();



        }

    }

    public  void signInVolley()
    {
        mQueue = CustomVolleyRequestQueue.getInstance(getActivity().getApplicationContext())
                .getRequestQueue();
        JSONObject params = new JSONObject();
        try {

            params.put("email_id", email.getText().toString());
            params.put("password",password.getText().toString());


        } catch (JSONException e) {
            e.printStackTrace();
        }

        final CustomJSONObjectRequest jsonRequest=new CustomJSONObjectRequest(Request.Method.POST, ApiClass.SignIn_URL,params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("aniloginsignin", response + "");
                try {

                    String successValue=response.getString("success");
                    Log.d("anisuccess",successValue);
                    Log.d("anilogin",successValue);
                    if(successValue.equals("1"))
                    {
                        JSONObject data=response.getJSONObject("data");
                        String name=data.getString("user_name");
                        Log.d("aniloginname",name);
                        Intent login = new Intent(getActivity(), HomeActivity.class);
                        SharedPref.Create_SharePref(getActivity(), name, "");
                        startActivity(login);
                        getActivity().finish();
                    }
                    else if(successValue.equals("0"))
                    {
                        Toast.makeText(myContext,"Invalid Email ID or Password",Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                Toast.makeText(getActivity(),"no internet connection",Toast.LENGTH_SHORT).show();
            }
        });

        mQueue.add(jsonRequest);
    }


}

1 个答案:

答案 0 :(得分:1)

尝试以下onConnectionFailed代码:

@Override
    public void onConnectionFailed(ConnectionResult connectionResult)
    {
Log.e(LOG_TAG, connectionResult.toString());
            //If connectionResult does not have resolution
            if(!connectionResult.hasResolution()){
                if (GoogleApiAvailability.getInstance().isUserResolvableError(connectionResult.getErrorCode())){
                    Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MainActivity.this, errorcode, REQUEST_CONSENT);
            dialog.show();
                    return;
                }

            }
            if(!mIsResolving ){
                    // The failure has a resolution. Resolve it.
                    // Called typically when the app is not yet authorized, and an
                    // authorization dialog is displayed to the user.
                    Log.d(LOG_TAG, "Attempting to Resolve Failed Connection");
                    mIsResolving = true;
                    try {
                connectionResult.startResolutionForResult(MainActivity.this, REQUEST_OAUTH);
            } catch (IntentSender.SendIntentException e) {
                Log.e(LOG_TAG,"Exception while starting Resolution Activity: "+e);
                e.printStackTrace();
            }
            }
        }

在你的onActivityResult中,获得结果:

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_OAUTH){
            mIsResolving = false;
            if (resultCode == RESULT_OK){
                if (mGoogleApiClient != null && !mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()){

                    mGoogleApiClient.connect();
                }
            }else {
                Log.d(LOG_TAG,"Result Code not OK");
            }
        }else {
            Log.d(LOG_TAG, "Request Code didn't match");
        }
    }