Creating Login button give ease to a user to provide authentic user login in his/her application. There are several ways a user can provide the login to the application such as using google, facebook, yahoo, linkedIn, etc. We will be looking forward to creating login for google, facebook, and Yahoo.
Creating login using Google
To create a login button for Google in your android application you first need to configure your application on console.developers.google.com. After this follow the following procedure -
- Add dependency in your manifest file
dependencies {
compile 'com.google.android.gms:play-services-auth:11.8.0'
}
- In your onCreate method for your activity add the following code by making the object of GoogleSignInOption to get the user details such as user id and other profile information
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
- Now create a GoogleSingnInClient to pass the options.
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
- After this process, you need to check if a user is already signed in, if yes then make the appropriate UI changes.
// Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
- In your layout file add the following code to get the google button.
<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
- By setting the onClick event on this button you can set this.
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
// ...
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN); }
- Now when a user Sign In the intent will be activated by which you can get the GoogleSignInAccount object.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
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);
}
}
- Using this account object you can get the user's email, user id, profile pic, etc.
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
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);
}
}
Creating Facebook LogIn button
To create login button for facebook you need to first create an app on developers.facebook.com. After this follow the following procedure -
- Add the gradle dependency in your app.gradle file.
implementation 'com.facebook.android:facebook-login:[4,5)'
- Add the following line of code in your manifest file to get the Facebook Activity class.
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
- After getting the activity set the button in your layout file
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
- Create a Login manager to get the login responses.
callbackManager = CallbackManager.Factory.create();
- Create an onClick event for your button using callback manager.
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
NOTE: You can register callback by using LoginManager or LoginButton if you set the callback using manager then you do not need to register the callback using LoginButton.
- At last, you need to call callbackManager.onActivityResult in your onActivityResult method to pass the login result to LoginManager via callbackManager.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
- Now you can check the login status of the user
boolean loggedIn = AccessToken.getCurrentAccessToken() == null;
- Now you can access the user profile by getting the tokens and managing the permissions.
Create Yahoo Login button
To create the yahoo login button you need to first register your app on devloper.yahoo.com. Follow the steps to integrate the Yahoo Login.
- Set some variables in your login activity.
String CONSUMER_KEY = "";
String CONSUMER_SECRET = "";
private String oAuthVerifier;
private CommonsHttpOAuthConsumer mainConsumer;
private CommonsHttpOAuthProvider mainProvider;
String CALLBACK_URL = OAuth.OUT_OF_BAND;
private static final String REQUEST_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_request_token";
private static final String ACCESS_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_access_token";
private static final String AUTHORIZE_WEBSITE_URL ="https://api.login.yahoo.com/oauth/v2/request_auth";
- Initialize your consumer and consumer provider
this.mainConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
this.mainProvider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_ENDPOINT_URL, ACCESS_TOKEN_ENDPOINT_URL, AUTHORIZE_WEBSITE_URL);
- Create the button in your layout file
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/request_yahoo"
android:layout_gravity="center_horizontal"
android:text="yahoo login"/>
- set onClick event for the button and call the OAuthRequestTokenTask by passing context consumer and oAuth provider.
class OAuthRequestTokenTask extends AsyncTask<Void, Void, String> {
final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
}
@Override
protected String doInBackground(Void... params) {
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer, CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
return url;
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
return null;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
Log.i(TAG, "onPostExecute result : " + result);
super.onPostExecute(result);
}
}
- After the execution of this Async Task, you need to access the token. For this, you need to execute another async task
public class OAuthGetAccessTokenTask extends AsyncTask<Void, Void, Void> { @Override
protected Void doInBackground(Void... arg0) {
try {
mainProvider.retrieveAccessToken(mainConsumer, oAuthVerifier);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
showToken();
}
}
- After this, you can call the Yahoo API to get the user profile information by writing the following method
public void getProfile(){
String guid = mainProvider.getResponseParameters().getFirst("xoauth_yahoo_guid");
String url = "https://social.yahooapis.com/v1/user/" + guid + "/profile?format=json";
this.doGet(url);
}
private void doGet(String url) {
OAuthConsumer consumer = this.mainConsumer;
final HttpGet request = new HttpGet(url);
Log.i("doGet","Requesting URL : " + url);
try {
Consumer.sign(request);
Log.i("YahooScreen", "request url : " + request.getURI());
new Thread(new Runnable() {
@Override
public void run() {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute((HttpUriRequest) request);
Log.i("doGet","Statusline : " + response.getStatusLine());
InputStream data = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(data));
String responeLine;
StringBuilder responseBuilder = new StringBuilder();
while ((responeLine = bufferedReader.readLine()) != null) {
responseBuilder.append(responeLine);
}
Log.i("doGet","Response : " + responseBuilder.toString());
//return responseBuilder.toString();
} catch (ClientProtocolException e) { // TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}).start();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
- To get the guid write the following method
public void getGUID(){
String GUID_URL="http://social.yahooapis.com/v1/me/guid?format=json";
this.doGet(GUID_URL);
}
Leave Comment