如何使用Google Drive Android Api从Google帐户退出并再次显示帐户选择器

时间:2014-11-25 11:54:10

标签: android google-drive-api google-drive-android-api

我已经实施了一项代码,可以通过开启者活动在Google云端硬盘Android应用中通过Google云端硬盘打开所选文件。在这个应用程序中,我需要放置注销选项来选择不同的帐户。但是此代码只会在我无法从我的应用程序中删除该登录用户后才签名一次。

是否可以使用Google Drive Android Api从Google帐户退出并再次显示帐户选择?

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...");
    }
}
}

1 个答案:

答案 0 :(得分:1)

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