Google 登录 - 登录指定帐户时出错

Google SignIn - Error signing in the specified account

我制作了一个使用用户的 gmail 帐户进行连接的应用程序。问题是它在设备上 运行 时完美运行,但在获得发布 apk 并将其安装在我的 phone 上后它只在第一次运行。如果我再次打开它,我会得到

"Error signing in the specified account. please choose a different account."

我注册到GoogleApiConsole的时候注意了。我注册的包的名称与清单中的名称相同,gradle,所以这不是问题。

我知道已经有很多问题与此有关,但 none 所提供的解决方案到目前为止对我有所帮助。 tips/ideas 有什么问题吗?

我的登录class

public class MainActivity extends Activity implements OnClickListener,
        ConnectionCallbacks, OnConnectionFailedListener {

    private static final int RC_SIGN_IN = 0;
    // Logcat tag
    private static final String TAG = "MainActivity";

    // Profile pic image size in pixels
    private static final int PROFILE_PIC_SIZE = 400;
    public static String username;
    public static String user_email;
    public static String user_pic;
    public static Person.Cover.CoverPhoto user_cover;



    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    /**
     * A flag indicating that a PendingIntent is in progress and prevents us
     * from starting further intents.
     */
    private boolean mIntentInProgress;

    private boolean mSignInClicked;

    private ConnectionResult mConnectionResult;

    private SignInButton btnSignIn;
    private Button btnSignOut, btnRevokeAccess;
    private ImageView imgProfilePic, logo;
    private TextView txtName, txtEmail;
    private LinearLayout llProfileLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (isNetworkAvailable()) {
        setContentView(imp.poinder.diana.track.R.layout.activity_main);


        btnSignIn = (SignInButton) findViewById(imp.poinder.diana.track.R.id.btn_sign_in);
        btnSignOut = (Button) findViewById(imp.poinder.diana.track.R.id.btn_sign_out);
        btnRevokeAccess = (Button) findViewById(imp.poinder.diana.track.R.id.btn_revoke_access);
        imgProfilePic = (ImageView) findViewById(imp.poinder.diana.track.R.id.imgProfilePic);
        txtName = (TextView) findViewById(imp.poinder.diana.track.R.id.txtName);
        txtEmail = (TextView) findViewById(imp.poinder.diana.track.R.id.txtEmail);
        llProfileLayout = (LinearLayout) findViewById(imp.poinder.diana.track.R.id.llProfile);
        logo = (ImageView) findViewById(imp.poinder.diana.track.R.id.poind2);

        // Button click listeners
        btnSignIn.setOnClickListener(this);
        btnSignOut.setOnClickListener(this);
        btnRevokeAccess.setOnClickListener(this);


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

        }
        else
        {
            startActivity(new Intent(MainActivity.this, NoInternetConnection.class));
        }
    }

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

    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

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

    @Override
    public void onConnected(Bundle arg0) {

        mSignInClicked = false;
        Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();

        // Get user's information
        getProfileInformation();

        // Update the UI after signin
        updateUI(true);

    }

    /**
     * Updating the UI, showing/hiding buttons and profile layout
     * */
    private void updateUI(boolean isSignedIn) {


        if (isSignedIn) {

            startActivity(new Intent(MainActivity.this, myprofile.class));
            /*/
            btnSignIn.setVisibility(View.GONE);
            btnSignOut.setVisibility(View.VISIBLE);
            btnRevokeAccess.setVisibility(View.VISIBLE);
            llProfileLayout.setVisibility(View.VISIBLE);
            logo.setVisibility(View.GONE);
            /*/
        } else {
            btnSignIn.setVisibility(View.VISIBLE);
            btnSignOut.setVisibility(View.GONE);
            btnRevokeAccess.setVisibility(View.GONE);
            llProfileLayout.setVisibility(View.GONE);
        }

    }

    /**
     * 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);
                //Person.Cover.CoverPhoto cover = currentPerson.getCover().getCoverPhoto();

                username = personName;
                user_email = email;
               // user_cover = cover;
                user_pic = personPhotoUrl;

                //add user to the USERS DATABASE
                add_user(personName,email);


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

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(imp.poinder.diana.track.R.menu.menu_main, menu);
        return true;
    }

    /**
     * Button on click listener
     * */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case imp.poinder.diana.track.R.id.btn_sign_in:
                // Signin button clicked
                signInWithGplus();
                break;
            case imp.poinder.diana.track.R.id.btn_sign_out:
                // Signout button clicked
                signOutFromGplus();
                break;
            case imp.poinder.diana.track.R.id.btn_revoke_access:
                // Revoke access button clicked
                revokeGplusAccess();
                break;
        }
    }

    /**
     * Sign-in into google
     * */
    private void signInWithGplus() {
        if (!mGoogleApiClient.isConnecting()) {
            mSignInClicked = true;
            resolveSignInError();
        }
    }

    /**
     * Sign-out from google
     * */
    public void signOutFromGplus() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();
            updateUI(false);
            logo.setVisibility(View.VISIBLE);

            Toast.makeText(this, "User is disconnected!", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Revoking access from google
     * */
    private void revokeGplusAccess() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
                    .setResultCallback(new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status arg0) {
                            Log.e(TAG, "User access revoked!");
                            mGoogleApiClient.connect();
                            updateUI(false);
                        }

                    });
            logo.setVisibility(View.VISIBLE);
        }
    }



    /**
     * Background Async task to load user profile picture from url
     * */
    private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public LoadProfileImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }

    // ADD USER TO THE DATABASE
    void add_user(String txtName, String txtEmail)
    {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        InputStream is = null;

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("user", txtName));
        nameValuePairs.add(new BasicNameValuePair("email", txtEmail));

        try {
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost("http:/xxxxx/users_in.php");
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            String msg = "Data has been sent successfully";
            //Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
        } catch (ClientProtocolException e) {
            Log.e("ClientProtocol", "Log_Tag");
            e.printStackTrace();
            String msg2 = "Log_Tag";
            Toast.makeText(getApplicationContext(), msg2, Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Log.e("Log_Tag", "No Internet Connection!");
            e.printStackTrace();
            String msg3 = "IOException";
            Toast.makeText(getApplicationContext(), msg3, Toast.LENGTH_LONG).show();
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

您需要从 google 开发者控制台为您的应用程序创建客户端 ID,以便使用 google 登录您的签名 apk。因此,使用凭据(程序包名称和 sha)创建客户端 ID,您的应用程序将正常运行。