Skip to content

Instantly share code, notes, and snippets.

@chandruark
Created February 28, 2018 10:53
Show Gist options
  • Save chandruark/0ac17cddc243e669a105fca06f0ed4e3 to your computer and use it in GitHub Desktop.
Save chandruark/0ac17cddc243e669a105fca06f0ed4e3 to your computer and use it in GitHub Desktop.
Social Login Activity in Single Page- Twitter, Facebook, Google which takes img, name,access tokens etc.
package com.example.chandru.remainder.SocialLogins;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.chandru.remainder.R;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.Task;
import com.twitter.sdk.android.core.DefaultLogger;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterAuthToken;
import com.twitter.sdk.android.core.TwitterConfig;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
import com.twitter.sdk.android.core.models.User;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import retrofit2.Call;
import static android.provider.ContactsContract.Intents.Insert.EMAIL;
public class FacebookLoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private static final String TAG ="FacebookLoginActivity" ;
CallbackManager callbackManager;
LoginButton loginButton1;
TwitterLoginButton loginButton;
ProfileTracker profileTracker;
ImageView imageView;
TwitterSession session;
SignInButton signInButton;
Button signOutButton;
private int RC_SIGN_IN = 0;
private GoogleSignInClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callbackManager = CallbackManager.Factory.create();
// getKeyHash();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = GoogleSignIn.getClient(this, gso);
FacebookSdk.sdkInitialize(getApplication());
TwitterConfig config = new TwitterConfig.Builder(getApplication())
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig( " your consumer key", "your consumer Secret token"))
.debug(true)
.build();
Twitter.initialize(config);
setContentView(R.layout.activity_facebook_login);
checkForInstagramData();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
imageView=(ImageView)findViewById(R.id.facebook_img);
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
Button instabtn = (Button) findViewById(R.id.insta_sign_in);
loginButton1 = (LoginButton) findViewById(R.id.login_button_f);
loginButton1.setReadPermissions(Arrays.asList(EMAIL));
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signInIntent = mGoogleApiClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
instabtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signInWithInstagram();
Toast.makeText(FacebookLoginActivity.this, "next Update", Toast.LENGTH_SHORT).show();
}
});
loginButton1.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("REsults",""+loginResult.getAccessToken().toString());
Log.d("REsults",""+loginResult.getRecentlyGrantedPermissions().toString());
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
/*Twitter
login
*/
loginButton = (TwitterLoginButton) findViewById(R.id.login_button_twitter);
loginButton.setCallback(new com.twitter.sdk.android.core.Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
Log.d("Twitter","success");
Log.d("Twitter",result.data.getUserName().toString());
TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
Log.d("Twitter",""+token);
Log.d("Twitter",""+secret);
Call<User> user = TwitterCore.getInstance().getApiClient().getAccountService().verifyCredentials(false, false,false);
user.enqueue(new com.twitter.sdk.android.core.Callback<User>() {
@Override
public void success(Result<User> result) {
String name = result.data.name;
String email = result.data.email;
String photoUrlOriginalSize = result.data.profileImageUrl.replace("_normal", "");
Log.d("Twitter",photoUrlOriginalSize.toString()+result.data.email+result.data.name);
Glide.with(getApplication())
.load(photoUrlOriginalSize.toString())
.into(imageView);
}
@Override
public void failure(TwitterException exception) {
Log.d("Twitter", "Verify Credentials Failure");
}
});
// TwitterAuthClient authClient = new TwitterAuthClient();
// authClient.requestEmail(session,new com.twitter.sdk.android.core.Callback<String>()
//
// {
// @Override
// public void success (Result < String > result) {
// // Do something with the result, which provides the email address
// Log.d("Twitter", "" + result);
// }
//
// @Override
// public void failure (TwitterException exception){
// // Do something on failure
// }
// });
}
@Override
public void failure(TwitterException exception) {
}
});
ProfileTracker profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
Log.d("loginimage",currentProfile.getProfilePictureUri(200,200).toString());
Log.d("loginimage",currentProfile.getLinkUri().toString()+""+currentProfile.getName().toString());
Glide.with(getApplicationContext())
.load(currentProfile.getProfilePictureUri(600,600))
.into(imageView);
}
};
}
private void signInWithInstagram() {
final Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme("https")
.authority("api.instagram.com")
.appendPath("oauth")
.appendPath("authorize")
.appendQueryParameter("client_id", "0fcd4d9343d142ff9d08e5ecfa841f1a")
.appendQueryParameter("redirect_uri", "sociallogin://redirect")
.appendQueryParameter("response_type", "token");
final Intent browser = new Intent(Intent.ACTION_VIEW, uriBuilder.build());
startActivity(browser);
}
private void checkForInstagramData() {
final Uri data = this.getIntent().getData();
if(data != null && data.getScheme().equals("sociallogin") && data.getFragment() != null) {
final String accessToken = data.getFragment().replaceFirst("access_token=", "");
if (accessToken != null) {
// handleSignInResult(...);
Log.d(TAG,""+accessToken.toString());
} else {
// handleSignInResult(...);
}
}
}
private void getKeyHash() {
PackageInfo info;
try {
info = getPackageManager().getPackageInfo("com.example.chandru.remainder", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
@Override
public void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
}
private void updateUI(GoogleSignInAccount signedIn) {
if(signedIn == null){
Toast.makeText(this, "not logined", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, " loged part ", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
loginButton.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
@SuppressLint("StringFormatInvalid")
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
account.getPhotoUrl();
Log.d(TAG,""+account.getPhotoUrl());
Glide.with(getApplication())
.load(account.getPhotoUrl().toString())
.into(imageView);
updateUI(account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
updateUI(null);
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment