Login with facebook api android

Integrating the Facebook API with Android

This article was updated on 13th December, 2016.

In this tutorial, I will show how to connect your Android application to the Facebook API. Lots of mobile applications use the Facebook API v4.x for login, signup and posting data.

Create Android Project

Make sure you have an up to date version of Android Studio. I am using version 1.4.1

Open Android Studio and create a New Project, naming it as you wish. Click Next, choose Minimum API level 17 and click Next again. Choose Empty Activity as the first activity, name it LoginActivity and click Finish.

Next, we add another blank activity to the project. Right Click the package and select New -> Activity -> Blank Activity. Leave its name as default and click finish.

The final project for this article can be found on Github. Make sure you change the Facebook API details to match you own.

Creating Facebook App ID

To use the Facebook API we have to add an app entry to our Facebook Developer Apps dashboard. You will need a Facebook developer account if you don’t have one already. Choose a random category and click Create App ID.

On the next page, scroll down to the bottom and complete both fields with the project packages names.

Now we need to add a Development Key Hash. There are two ways of generating one. The first option is using the command line.

Windows

Open Facebook’s My Apps section and copy the App ID:

Open strings.xml in your project and add this line of code:

Setting up Facebook SDK

Open build.gradle (Project) and add mavenCentral() to both repository sections. Then open build.gradle (Module) and add the SDK library by adding this line to dependencies :

Now sync gradle.

Activities and Layouts

Open AndroidManifest.xml and make these changes.

Change the MainActivity label:

Now we are going to work with Java classes and layouts.

First, we are going to work with LoginActivity.java. This class opens an authenticated connection to the Facebook API and gets data from it.

Add these lines before the onCreate method inside the class:

Here we create a FacebookCallback called callback . This executes the next action after we get a response from the Facebook API and the method for that is onSuccess() .

Inside the onSuccess method we create a new Facebook Profile and get data for that profile. Later we will create a simple function called nextActivity() that will switch our activity.

We are going to initialize the Facebook SDK so we can use its functions and methods. Inside onCreate() add these lines:

Next, we need to show the famous Facebook Log in button. We don’t need to make it from scratch as it exists inside the SDK’s libraries and can be called in our layout.

So we will edit our LoginActivity’s layout. It’s name should be content_login.xml . In fact, the latest version of Android Studio creates two default .xml files for every activity we create. The other layout file is called activity_login.xml .

Читайте также:  Как прошить андроид китай

In activity_login.xml delete the code for the floating button as we won’t need it.

In content_login.xml there is only a TextView element. We will remove it and create a new LinearLayout that is horizontally oriented. Inside that layout we will add the log in button. Paste the code below to replace the current contents of content_login.xml:

I added some padding at the top and bottom and centered the horizontal linear layout. Let’s return to the Login class and create the button.

Inside the onCreate() method before the closing bracket, add the code below:

Here we create a connection between the button in content_login.xml and the Facebook SDK libraries.

There are some @Overrided methods that we need inside LoginActivity.java. Add the lines below:

The last function in this class is nextActivity() which will switch activities and pass data to the next activity.

We need the first and last name of the profile and a 200 by 200-pixel profile picture. At this stage, we only get its Uri . These three strings will be used as extras in our next activity.

MainActivity class

The nextActivity() function in the LoginActivity class passed some strings to our next activity. Now we use them by creating three other strings inside the onCreate() method of the MainActivity class and storing the passed data in them:

To display this data we need to change the content_main.xml layout. The code below adds the elements we need to display the data. Add this code inside the RelativeLayout tags:

To display the profile name add the code below to the onCreate() method of the MainActivity class:

Next, we want to display the profile picture. From the last activity, we have the picture Uri as a string. We can use this Uri to download the picture as a Bitmap file.

Create a new class, and add the code below:

To display the profile picture in our app, add the line below inside the onCreate() method of the MainActivity class, after the last line added.

It uses the imageUrl string, downloads the image and displays it inside the content_main.xml layout.

Now that displaying data is complete, we will add a share dialog to the floating action button so the app can post to Facebook.

Open activity_main.xml and change:

Change the button color by editing the color values in colors.xml. I used this color:

Next to make the button do something.

Declare a private ShareDialog variable in the MainActivity class:

Inside the onCreate() method create this dialog:

We want to show this dialog when we click the floating button. Replace the Snackbar code in the OnClick method with the code below:

Our app can now post to Facebook, but we are not finished yet, the Logout function is missing.

First the app needs to understand if it is logged in. Initialize the Facebook SDK as we did in LoginActivity by adding this line of code inside the onCreate() method:

Add the logout() function:

Now you can run your app and post to Facebook! Please let me know in the comments below if you have any problems or questions.

Источник

Quick Tip: Add Facebook Login to Your Android App

Facebook Login provides a convenient and secure way for people to log in to an app without having to go through a sign-up process first. Using the latest version of Facebook’s SDK for Android, it takes only a few minutes to add this feature to your app.

Читайте также:  Операционная система android для персонального компьютера

In this quick tip, you will learn how to add a Facebook login button to an Android app and handle the events to log a user in using Facebook Login.

Premium Option

If you want a quick solution for setting up user authentication in your Android apps, try Android Authentication System on Envato Market. It’s a source code project that lets developers create signups and logins and authorize users for their app.

Android Authentication System on Envato Market

You can also find Android developers on Envato Studio to help you with your projects.

Prerequisites

Before you begin, make sure you have access to the following:

1. Register Your App

All apps that use the Facebook SDK must be registered with Facebook. Log in to the Facebook Developers website and click Create a New App in the top right.

You are presented with a form that asks for the app’s Display Name, Namespace, and Category. Enter the required fields and click Create App ID.

In the next screen, you are able to see your Application ID. Make a note of it, because you will be needing it later in this tutorial.

Open Settings from the left and click the Add Platform button. From the pop-up, select Android.

In the next form, enter the package name of your app and the name of your Activity . If you haven’t created your app or Activity yet, make sure you remember the values you entered.

To fill in the Key Hashes field, open a terminal window and run the keytool command to generate a key hash using the debug keystore located at

/.android/debug.keystore. This is what the command should look like.

The default password for the debug keystore is android. Enter that password when prompted. The output of the command should be a string of 28 characters. Copy it, go back to your browser, and paste the string into the Key Hashes field as shown below.

Make sure Single Sign On is set to Yes and click the Save Changes button. Your app is now registered.

2. Add Facebook SDK to Your Project

The Facebook SDK is available on Maven Central. To use this repository, edit the build.gradle file in your project’s app directory and add the following code to it before the list of dependencies:

You can now add the Facebook SDK to your project as a compile dependency. Add the following code to the list of dependencies:

3. Create an Activity

Step 1: Define the Layout

Create a new layout named main_activity.xml in res/layout. This is going to be a very simple layout with only two widgets:

  • a LoginButton to allow the user to log in to Facebook
  • a TextView to display the result of the latest login attempt

You can place them inside a RelativeLayout . After including attributes for padding and positioning the widgets, the layout’s XML will look something like this:

Step 2: Create the Class

Create a new Java class that extends Activity and name it MainActivity.java. Remember that the name of this class and the package that it belongs to should match the values you entered while registering your app with Facebook.

Declare the widgets you defined in the activity’s layout as fields of this class.

Читайте также:  Android app icon launcher icon

Declare a CallbackManager as another field. The CallbackManager , as its name suggests, is used to manage the callbacks used in the app.

The SDK needs to be initialized before using any of its methods. You can do so by calling sdkInitialize and passing the application’s context to it. Add the following code to the onCreate method of your Activity :

Next, initialize your instance of CallbackManager using the CallbackManager.Factory.create method.

Call setContentView to set the layout defined in the previous step as the layout of this Activity and then use findViewById to initialize the widgets.

It’s time to create a callback to handle the results of the login attempts and register it with the CallbackManager . Custom callbacks should implement FacebookCallback . The interface has methods to handle each possible outcome of a login attempt:

  • If the login attempt is successful, onSuccess is called.
  • If the user cancels the login attempt, onCancel is called.
  • If an error occurs, onError is called.

To register the custom callback, use the registerCallback method. The code to create and register the callback should look like this:

You can now add code to these methods to display appropriate messages using the setText method of the TextView .

When the onSuccess method is called, a LoginResult is passed as a parameter. Retrieve the access token it contains using getAccessToken and use its getUserId method to get the user’s ID. To get the token in the form of a String , use getToken . Display these values in the TextView by adding the following code to the onSuccess method:

If the user cancel’s the login attempt, we display a message saying «Login attempt canceled». Add the following code to the onCancel method:

Similarly, add the following code to the onError method:

Tapping the login button starts off a new Activity , which returns a result. To receive and handle the result, override the onActivityResult method of your Activity and pass its parameters to the onActivityResult method of CallbackManager .

4. Add the Facebook Application ID

The application ID you received when you registered your app should be added as a string in your project’s res/values/strings.xml. For this tutorial, call the string facebook_app_id.

5. Edit the Manifest

Define your Activity in the AndroidManifest.xml. If it is the first Activity of your app, you should also add an intent-filter that responds to the action android.intent.action.MAIN .

Add the application ID as meta-data .

Define FacebookActivity as another Activity that belongs to your app. It handles most of the configuration changes itself. You need to mention that using the configChanges attribute.

Finally, you have to request android.permission.INTERNET to be able to connect to Facebook’s servers.

6. Build and Run

Your app is now complete. When you build it and deploy it on your Android device, you will see the Facebook login button.

Tapping the login button takes you to a Facebook page that asks you to log in and authorize the app.

After successfully logging in, the TextView will display the user ID and auth token.

Conclusion

In this quick tip, you learned how to use the Facebook SDK to add Facebook Login to your Android app. You also learned how to handle the possible outcomes of a login attempt. To learn more about Facebook Login, you can go through the reference for the Facebook SDK for Android.

Источник

Оцените статью