简体   繁体   中英

how to sign out from Google Account and show account chooser again using Google Drive Android Api

I have implemented a code to open the selected file from Google Drive on Google Drive Android Application through opener activity. In this application i need to place sign out option to choose different account. But this code will ask sign in only once after that i cant remove that signed-in user from my application.

Is it possible to sign out from Google account and show account chooser again using Google Drive Android Api ?

BaseDemoActivity.java

public abstract class BaseDemoActivity extends Activity implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private static final String TAG = "BaseDriveActivity";

/**
 * DriveId of an existing folder to be used as a parent folder in
 * folder operations samples.
 */
public static final String EXISTING_FOLDER_ID = "folderid";

/**
 * DriveId of an existing file to be used in file operation samples..
 */
public static final String EXISTING_FILE_ID = "fileid";

/**
 * Extra for account name.
 */
protected static final String EXTRA_ACCOUNT_NAME = "account_name";

/**
 * Request code for auto Google Play Services error resolution.
 */
protected static final int REQUEST_CODE_RESOLUTION = 1;

/**
 * Next available request code.
 */
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;

/**
 * Google API client.
 */
private GoogleApiClient mGoogleApiClient;

/**
 * Called when activity gets visible. A connection to Drive services need to
 * be initiated as soon as the activity is visible. Registers
 * {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the
 * activities itself.
 */
@Override
protected void onResume() {
    super.onResume();
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    mGoogleApiClient.connect();
}

/**
 * Handles resolution callbacks.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode,
        Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
        mGoogleApiClient.connect();
    }
}

/**
 * Called when activity gets invisible. Connection to Drive service needs to
 * be disconnected as soon as an activity is invisible.
 */
@Override
protected void onPause() {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
    super.onPause();
}

/**
 * Called when {@code mGoogleApiClient} is connected.
 */
@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "GoogleApiClient connected");
}

/**
 * Called when {@code mGoogleApiClient} is disconnected.
 */
@Override
public void onConnectionSuspended(int cause) {
    Log.i(TAG, "GoogleApiClient connection suspended");
}

/**
 * Called when {@code mGoogleApiClient} is trying to connect but failed.
 * Handle {@code result.getResolution()} if there is a resolution is
 * available.
 */
@Override
public void onConnectionFailed(ConnectionResult result) {
    Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
    if (!result.hasResolution()) {
        // show the localized error dialog.
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
        return;
    }
    try {
        result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
    } catch (SendIntentException e) {
        Log.e(TAG, "Exception while starting resolution activity", e);
    }
}

/**
 * Shows a toast message.
 */
public void showMessage(String message) {
    Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}

/**
 * Getter for the {@code GoogleApiClient}.
 */
public GoogleApiClient getGoogleApiClient() {
  return mGoogleApiClient;
}
}

MainActivity.java

public class MainActivity extends BaseDemoActivity {

private static final String TAG = "MainActivity";
private static final int RC_SIGN_IN = 0;
private boolean mIntentInProgress;
private ConnectionResult mConnectionResult;
private static final int REQUEST_CODE_OPENER = 1;
private boolean browsefile = false;
private boolean mSignInClicked; 
private String FILE_ID;
TextView filepath;
Button choosefilebutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    choosefilebutton = (Button) findViewById(R.id.choosefilebutton);
    filepath = (TextView) findViewById(R.id.filepath);
    choosefilebutton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            open();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
     MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.main, menu);
     return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
  case R.id.action_logout:
      signOutFromGplus();
      choosefilebutton.setVisibility(View.GONE);
    break;

  default:
    break;
  }

  return true;
}

@Override
public void onConnected(Bundle connectionHint) {
    super.onConnected(connectionHint);
    //mSignInClicked = false;
}

private void open(){
    IntentSender intentSender = Drive.DriveApi
            .newOpenFileActivityBuilder()
            .build(getGoogleApiClient());
    try {
        browsefile = true;
        startIntentSenderForResult(
                intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
    } catch (SendIntentException e) {
      Log.w(TAG, "Unable to send intent", e);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_CODE_OPENER:
        if (resultCode == RESULT_OK && browsefile == true) {
            showMessage("Result ok...");

            if (!getGoogleApiClient().isConnecting()) {
                getGoogleApiClient().connect();
            }
             DriveId driveId = (DriveId) data.getParcelableExtra(
                     OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
             showMessage("Selected file's ID: " + driveId.getResourceId());
             FILE_ID = driveId.getResourceId();
             if(FILE_ID != null){
                String link = "https://docs.google.com/file/d/"+FILE_ID;
                filepath.setText(link);
                Uri path = Uri.parse(link);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(path);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    showMessage(e.getMessage());
                }
            }

        }
        //finish();
        break;
    default:
        super.onActivityResult(requestCode, resultCode, data);
    }
}

/**
 * Sign-out from google
 * */
private void signOutFromGplus() {
    if (getGoogleApiClient().isConnected()) {
        getGoogleApiClient().disconnect();
        showMessage("Sign out Success...");
    }
}
}

看看我在SO 21610239中的回答,特别是UPDATE 2014-11-04部分。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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