我尝试过使用开发者网站上提供的google登录文档中的代码。我想知道我们该怎么做? 我在其他活动中创建了按钮,并且想要在单击按钮并清除会话时调用signout方法。
此外,当我使用应用程序登录一次时,如何从下次恢复会话。我再次必须开始登录。有没有办法做到这一点?
这是我的代码:
public class GoogleSign extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG_GPLUS = "GoogleSign";
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 700;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
//Tag used for GoogleSign
private static final String TAG = "GoogleSign";
UserFunctions userFunction;
/**
* 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,btnproceed;
private ImageView imgProfilePic;
private TextView txtName, txtEmail;
private LinearLayout llProfileLayout;
private RegisterCommuterStructure mRegisterCommuterDetails;
String gname,ggender, phoneno, gemail, gbday;
String tag = "google";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_sign);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
//btnproceed = (Button) findViewById(R.id.btn_proceed);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
mRegisterCommuterDetails = new RegisterCommuterStructure();
userFunction = new UserFunctions();
/*btnproceed.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
proceed();
}
});*/
// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
btnRevokeAccess.setOnClickListener(this);
//GoogleApi Client handling
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
}
protected void onStart()
{
System.out.println("onstart");
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop()
{
System.out.println("onstop");
super.onStop();
if (mGoogleApiClient.isConnected())
{
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError()
{
System.out.println("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)
{
System.out.println("onConnectionFailed");
if (!result.hasResolution())
{
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
String r= result.toString();
Log.i("error",r);
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)
{
System.out.println("onActivityResult");
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK)
{
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting())
{
mGoogleApiClient.connect();
}
}
}
@Override
public void onConnected(Bundle arg0)
{
System.out.println("onConnected");
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)
{
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
}
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()
{
//JSONObject json = userFunction.registerUser(gname, phoneno,gemail,gbday,ggender);
try
{
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null)
{
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
Integer gender_id = currentPerson.getGender();
String bDate = currentPerson.getBirthday();
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName);
Log.e(TAG ,"plusProfile: "+ personGooglePlusProfile );
Log.e(TAG ,"email: " + email);
Log.e(TAG ,"PhotoURL"+ personPhotoUrl);
Log.e(TAG_GPLUS, "Gender ID = " + gender_id);
Log.e(TAG_GPLUS, "BirthDate = " + bDate);
try
{
JSONObject jObj = new JSONObject();
jObj.put("tag",tag);
jObj.put("name",personName);
jObj.put("bday",bDate);
jObj.put("gender", gender_id);
jObj.put("email", email);
mRegisterCommuterDetails.setCommuterName(personName);
mRegisterCommuterDetails.setEmail(email);
mRegisterCommuterDetails.setGender(gender_id.toString());
mRegisterCommuterDetails.setDob(bDate);
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
new RegisterTask().execute();
txtName.setText(personName);
txtEmail.setText(email);
proceed();
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0, personPhotoUrl.length() - 2) + PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
/* Intent i = new Intent(GoogleSign.this,MainGoogleActivity.class);
startActivity(i);*/
}
else
{
Toast.makeText(getApplicationContext(), "Sorry,Person information is null", Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
protected void proceed()
{
Intent intent= new Intent(GoogleSign.this, MainGoogleActivity.class);
intent.putExtra("user", mRegisterCommuterDetails.getCommuterName());
startActivity(intent);
}
@Override
public void onConnectionSuspended(int arg0)
{
System.out.println("onConnectionSuspended");
mGoogleApiClient.connect();
updateUI(false);
}
/**
* Button on click listener
* */
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case 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
* */
private void signOutFromGplus()
{
if (mGoogleApiClient.isConnected())
{
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
/**
* 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);
}
});
}
}
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);
}
}
public class RegisterTask extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(Void... params) {
if (!NetworkUtility.isNetworkConnected(GoogleSign.this)) {
return getString(R.string.internet_fail);
}
String lValue = TuksiCommuterServerUtilsGoogle.getRegistrarionResponse(GoogleSign.this, mRegisterCommuterDetails);
if (lValue != null) {
return lValue;
}
return null;
}
}
}