谷歌登录问题

时间:2015-12-22 06:58:56

标签: android google-signin

在我的Android应用程序中实施谷歌登录,因为我可以在成功登录后使用谷歌登录登录,我想从登录页面重定向到我的homepageactvity.But从主页活动我可以退出(断开谷歌api客户端),当再次点击退出按钮时,主动性即将到来..请帮助我解决这个问题。我的登录行为低于

public class LoginActivityGoogle extends Activity implements OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private static final int RC_SIGN_IN = 0;

// Google client to communicate with Google
private GoogleApiClient mGoogleApiClient;
private String TAG = "Login";

private boolean mIntentInProgress;
private boolean signedInUser;
private ConnectionResult mConnectionResult;
private SignInButton signinButton;
private ImageView image;
private TextView username, emailLabel;
private LinearLayout profileFrame, signinFrame;
SessionManager session;
private boolean mSignInClicked;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_google);

    signinButton = (SignInButton) findViewById(R.id.signin);
    signinButton.setOnClickListener(this);

    image = (ImageView) findViewById(R.id.image);
    username = (TextView) findViewById(R.id.username);
    emailLabel = (TextView) findViewById(R.id.email);

    profileFrame = (LinearLayout) findViewById(R.id.profileFrame);
    signinFrame = (LinearLayout) findViewById(R.id.signinFrame);
    session = new SessionManager(getApplicationContext());

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Plus.API)
            .addScope(new Scope(Scopes.PROFILE))
            .addScope(new Scope(Scopes.EMAIL))

            .build();


}

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

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

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 mConnectionResult
        mConnectionResult = result;

        if (signedInUser) {
            resolveSignInError();
        }
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);

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

        signedInUser = false;
        mGoogleApiClient.connect();
    }
}

@Override
public void onConnected(Bundle arg0) {
    signedInUser = false;
    Toast.makeText(this, "Connected", Toast.LENGTH_LONG).show();


    // To launch from gere to homwpageactivity
    Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
    String personName = currentPerson.getDisplayName();
    String personPhotoUrl = currentPerson.getImage().getUrl();
    String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

    Intent in = new Intent(getApplicationContext(), HomePageActivity.class);

    in.putExtra("username",personName);
    in.putExtra("email",email);
    in.putExtra("profile_pic",personPhotoUrl);
    startActivity(in);
    getProfileInformation();
}

private void updateProfile(boolean isSignedIn) {
    if (isSignedIn) {
        signinFrame.setVisibility(View.GONE);
       // profileFrame.setVisibility(View.VISIBLE);

    } else {
        signinFrame.setVisibility(View.VISIBLE);
        //profileFrame.setVisibility(View.GONE);
    }
}

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 email = Plus.AccountApi.getAccountName(mGoogleApiClient);


            updateProfile(true);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onConnectionSuspended(int cause) {
    mGoogleApiClient.connect();
    updateProfile(false);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.signin:
            googlePlusLogin();
            break;
    }
}

public void signIn(View v) {
    googlePlusLogin();
}



private void googlePlusLogin() {
    if (!mGoogleApiClient.isConnecting()) {
        signedInUser = true;
        resolveSignInError();
    }
}

private void googlePlusLogout() {
    if (mGoogleApiClient.isConnected()) {
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();
        updateProfile(false);
    }
}

// download Google Account profile image, to complete profile
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
    ImageView downloadedImage;

    public LoadProfileImage(ImageView image) {
        this.downloadedImage = image;
    }

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

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

我的主页是

 public class HomePageActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,View.OnClickListener,
GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener
{

    private SharedPreferences preferences;
    ConnectionDetector cd;
    AlertDialogManager alert = new AlertDialogManager();
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        cd = new ConnectionDetector(this);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View header=navigationView.getHeaderView(0);
        TextView username=(TextView) header.findViewById(R.id.username);
        TextView user_email=(TextView) header.findViewById(R.id.email);
        ImageView profileImage=(ImageView) header.findViewById(R.id.imageView) ;
        String user_name= getIntent().getStringExtra("username");
        String user_gmail= getIntent().getStringExtra("email");
        String profile_pic=getIntent().getStringExtra("profile_pic");
        username.setText(user_gmail);
        user_email.setText(user_name);
         CardView card_attendance = (CardView) findViewById(R.id.card_attendance);
        CardView card_assignment = (CardView) findViewById(R.id.card_assignment);
        CardView card_circular = (CardView) findViewById(R.id.card_circular);
        CardView card_communication = (CardView) findViewById(R.id.card_communication);
        CardView card_Fee = (CardView) findViewById(R.id.card_Fee);
        CardView card_Library = (CardView) findViewById(R.id.card_Library);
        CardView card_Result = (CardView) findViewById(R.id.card_Result);
        CardView card_StudyMat = (CardView) findViewById(R.id.card_StudyMat);

        card_attendance.setOnClickListener(this);
        card_assignment.setOnClickListener(this);
        card_circular.setOnClickListener(this);
        card_communication.setOnClickListener(this);
        card_Fee.setOnClickListener(this);
        card_Library.setOnClickListener(this);
        card_Result.setOnClickListener(this);
        card_StudyMat.setOnClickListener(this);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API)
                .addScope(new Scope(Scopes.PROFILE))
                .addScope(new Scope(Scopes.EMAIL))

                .build();
    }
       @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_change_pass) {
            Intent intent = new Intent(HomePageActivity.this, ChangePasswordActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_logout) {

            googlePlusLogout();

        }
        else if (id == R.id.nav_faq) {
            Intent intent = new Intent(HomePageActivity.this, FAQActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_about) {
            PopupAbout();
        } else if (id == R.id.nav_share) {
            shareApp();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.card_attendance:
                Intent intent = new Intent(HomePageActivity.this, AttendanceActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            case R.id.card_assignment:
                Intent intent2 = new Intent(HomePageActivity.this, AssignmentActivity.class);
                intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent2);
                break;
            case R.id.card_StudyMat:
                Intent intent3 = new Intent(HomePageActivity.this, StudyMaterialListActivity.class);
                intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent3);
                break;
            case R.id.card_Library:
                Intent intent4 = new Intent(HomePageActivity.this, LibraryActivity.class);
                intent4.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent4);
                break;
            case R.id.card_Result:
                Intent intent5 = new Intent(HomePageActivity.this, ResultActivity.class);
                intent5.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent5);
                break;
            case R.id.card_communication:
                Intent intent6 = new Intent(HomePageActivity.this, CommunicationActivity.class);
                intent6.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent6);
                break;
            case R.id.card_Fee:
                Intent intent7=new Intent(HomePageActivity.this,FeeActivity.class);
                intent7.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent7);
                break;
            case R.id.card_circular:
                Intent intent8=new Intent(HomePageActivity.this,CircularListActivity.class);
                intent8.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent8);
                break;
            default:
                break;
        }

    }
    private void shareApp() {
        try {
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.putExtra(Intent.EXTRA_SUBJECT, "Checkout The NI Model School App for Android");
            String sAux = "\nHi, I am using The NI Model School Android app to track my child's activities in school.\n";
            String sAux1 = sAux + "Why don't you check it out on your Android phone.\n";
            String sAux2 = sAux1 + "market://details?id="
                    + HomePageActivity.this.getPackageName() + "\n\n";
            i.putExtra(Intent.EXTRA_TEXT, sAux2);
            startActivity(Intent.createChooser(i, "choose one"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void PopupAbout() {
        AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(
                HomePageActivity.this);
        alertDialogBuilder1.setTitle(R.string.app_name);

        LayoutInflater li = LayoutInflater.from(HomePageActivity.this);
        final View pView = li.inflate(R.layout.alert_about, null);
        alertDialogBuilder1.setView(pView);
        alertDialogBuilder1.setIcon(R.mipmap.ic_launcher);
        alertDialogBuilder1.setCancelable(true);
        try {
            PackageInfo pInfo = HomePageActivity.this.getPackageManager()
                    .getPackageInfo(HomePageActivity.this.getPackageName(), 0);
            String version = pInfo.versionName;
            alertDialogBuilder1.setMessage("Version: " + version);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        alertDialogBuilder1.setPositiveButton("Rate",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        dialog.dismiss();
                        Uri uri = Uri.parse("market://details?id="
                                + HomePageActivity.this.getPackageName());
                        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                        goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY
                                | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                        try {
                            startActivity(goToMarket);
                        } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                            Toast.makeText(HomePageActivity.this,
                                    "Play Store unavailable..",
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder1.create();
        alertDialog.show();
    }

    @Override
    public void onConnected(Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }   private void googlePlusLogout() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
          mGoogleApiClient.connect();
            Intent intent = new Intent(HomePageActivity.this, LoginActivityGoogle.class);
            startActivity(intent);
    }
    }

2 个答案:

答案 0 :(得分:0)

enter image description here

从代码中删除图片中的选定行

答案 1 :(得分:0)

我解决了上述问题,实际上应用程序崩溃了因为我没有将谷歌客户端连接到我的Homepageactvity.So一旦我将谷歌客户端连接到我的Homepageactvity,那么我可以从我的注销应用程序。 首先,我将下面的代码放入我的On create method

 GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
            .requestEmail()
            .build();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

之后我调用了googlesignout的方法。它现在工作正常