Full Source Code Download Here:
https://github.com/sanjaymangaroliya/LoginWithFacebook
MainActivity
package com.sanjay.loginwithfacebook;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private Button btn_sign_in, btn_logout;
private ImageView img_profile;
private TextView tv_info;
private LoginButton loginButton;
private CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
callbackManager = CallbackManager.Factory.create();
initUI();
}
private void initUI() {
TextView tvTitle = findViewById(R.id.tv_title);
tvTitle.setText(getResources().getString(R.string.app_name));
btn_sign_in = findViewById(R.id.btn_sign_in);
btn_logout = findViewById(R.id.btn_logout);
img_profile = findViewById(R.id.img_profile);
tv_info = findViewById(R.id.tv_info);
loginButton = findViewById(R.id.login_button);
//Default Login Button
/* loginButton.setReadPermissions("public_profile", "email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Utils.showToast(MainActivity.this, "Login Successfully.");
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
getUserData(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email, gender, birthday, location");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
Utils.showToast(MainActivity.this, "Login Cancel.");
updateUI(false);
}
@Override
public void onError(FacebookException exception) {
Utils.showToast(MainActivity.this, "Login Error.");
updateUI(false);
}
});*/
}
//Custom Login Button
public void onClickSignIn(View view) {
if (Utils.isNetworkAvailable(this)) {
LoginManager.getInstance().logInWithReadPermissions(
this, Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(
callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Utils.showToast(MainActivity.this, "Login Successfully.");
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
getUserData(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email, gender, birthday, location");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
Utils.showToast(MainActivity.this, "Login Cancel.");
updateUI(false);
}
@Override
public void onError(FacebookException e) {
Utils.showToast(MainActivity.this, "Login Error.");
updateUI(false);
}
});
} else {
Utils.showAlertDialog(this, getResources().getString(R.string.alert)
, getResources().getString(R.string.internet_error));
}
}
//Get User Profile Information
private void getUserData(JSONObject object) {
try {
updateUI(true);
StringBuilder stringBuilder = new StringBuilder();
if (object.has("first_name")) {
stringBuilder.append("First Name: " + object.getString("first_name"));
}
if (object.has("last_name")) {
stringBuilder.append("\nLast Name: " + object.getString("last_name"));
}
if (object.has("email")) {
stringBuilder.append("\nEmail: " + object.getString("email"));
}
if (object.has("gender")) {
stringBuilder.append("\nGender: " + object.getString("gender"));
}
if (object.has("birthday")) {
stringBuilder.append("\nBirthday: " + object.getString("birthday"));
}
if (object.has("location")) {
stringBuilder.append("\nLocation: " + object.getJSONObject("location").getString("name"));
}
tv_info.setText(stringBuilder.toString());
//Profile Picture
String id = object.getString("id");
try {
URL profile_pic = new URL("https://graph.facebook.com/"
+ id + "/picture?");
Glide.with(getApplicationContext()).load(profile_pic.toString())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(img_profile);
} catch (MalformedURLException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
//UpDate UI
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btn_sign_in.setVisibility(View.GONE);
btn_logout.setVisibility(View.VISIBLE);
img_profile.setVisibility(View.VISIBLE);
tv_info.setVisibility(View.VISIBLE);
} else {
btn_sign_in.setVisibility(View.VISIBLE);
btn_logout.setVisibility(View.GONE);
img_profile.setVisibility(View.GONE);
tv_info.setVisibility(View.GONE);
}
}
//Facebook Logout
public void onClickLogout(View view) {
if (AccessToken.getCurrentAccessToken() == null) {
updateUI(false);
return;
}
new GraphRequest(AccessToken.getCurrentAccessToken(),
"/me/permissions/", null,
HttpMethod.DELETE, new GraphRequest
.Callback() {
@Override
public void onCompleted(GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
Utils.showToast(MainActivity.this, "Logout Successfully.");
updateUI(false);
}
}).executeAsync();
}
}
Utils.java
package com.sanjay.loginwithfacebook;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.widget.Toast;
public class Utils {
public static boolean isNetworkAvailable(Context context) {
if (context == null) {
return false;
}
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
public static void showToast(Context activity, String strMsg) {
Toast toast = Toast.makeText(activity, strMsg, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
public static void showAlertDialog(Context context, String title, String msg) {
AlertDialog.Builder adb = new AlertDialog.Builder(context);
adb.setTitle(title);
adb.setMessage(msg);
adb.setCancelable(false);
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
adb.create().show();
}
public static boolean isNotEmptyString(String str) {
if (str != "" && str != null && str.trim().length() > 0
&& !str.equalsIgnoreCase("null")) {
return true;
}
return false;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:fitsSystemWindows="true">
<include layout="@layout/toolbar" />
<android.support.v4.widget.NestedScrollView
android:id="@+id/nested_scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<RelativeLayout
android:id="@+id/rl_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp">
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:visibility="gone" />
<Button
android:id="@+id/btn_sign_in"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="@color/colorPrimary"
android:gravity="center"
android:onClick="onClickSignIn"
android:text="@string/sign_in"
android:textColor="@color/white"
android:visibility="visible" />
<Button
android:id="@+id/btn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_sign_in"
android:layout_marginTop="20dp"
android:background="@color/colorPrimary"
android:gravity="center"
android:onClick="onClickLogout"
android:text="@string/logout"
android:textColor="@color/white"
android:visibility="gone" />
<ImageView
android:id="@+id/img_profile"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btn_logout"
android:layout_marginTop="20dp"
android:src="@mipmap/ic_launcher"
android:visibility="gone" />
<TextView
android:id="@+id/tv_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_logout"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:layout_toRightOf="@+id/img_profile"
android:text="@string/name"
android:textColor="@color/colorPrimary"
android:textSize="16dp"
android:visibility="gone" />
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
toolbar.xml
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/tv_title"
style="@style/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sanjay.loginwithfacebook">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--Facebook-->
<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>
</application>
</manifest>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimary</item>
<item name="colorAccent">@color/colorPrimary</item>
<item name="windowActionBar">true</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="tv_title">
<item name="android:layout_gravity">center</item>
<item name="android:textColor">@color/white</item>
<item name="android:textSize">20sp</item>
<item name="android:textAllCaps">false</item>
<item name="android:textStyle">normal</item>
</style>
<style name="textView">
<item name="android:singleLine">true</item>
<item name="android:textAllCaps">false</item>
</style>
</resources>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.sanjay.loginwithfacebook"
minSdkVersion 16
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
//Support Design
compile 'com.android.support:design:26+'
//Facebook
implementation 'com.facebook.android:facebook-login:[4,5)'
//Glide Image
compile 'com.github.bumptech.glide:glide:3.7.0'
}
No comments:
Post a Comment