Android facebook login

In your application, you might want to use Facebook Login to authenticate users that use your application. In this Android tip, I am going to show you how to achieve this goal using Facebook SDK.
To implement login in your application using Facebook Login API, first you need to download the Facebook SDK for Android from the https://developers.facebook.com/resources/facebook-android-sdk-current.zip link. Then extract the zip in a folder that you can easily find it.
In this tip, the example application will run on the real device. So, you need to install the Facebook App on your device from Google Play.
Next, you create a new Android project in Eclipse ADT. You will import the Facebook project extracted from the zip file to your project (import->General->Existing Projects to Workspace). To add the Facebook project to your project, view Properties of the project. You select Android tab. In the lower part of the dialog, click Add. Choose the FacebookSDK project from the workspace. You might get errors after adding the Facebook project. If the error says "Unable to resolve target 'android-9' ", you need to use SDK Manager to install the Android SDK level 9. If you get dependency error (e.g. facebooksdk.jar missing from Android Dependencies library
), you need to clean and rebuild the project.

If you do not create an app in https://developers.facebook.com, please create it. After you create the app, you will get an App ID. The App ID will be used in your Android project.




In the values/string.xml file of your Android project, you need to add a new entry with the name "facebook_app_id" and value "your App ID". For example, you add the line: <string name="facebook_app_id">907564268679845</string> to the strings.xml file.

In the AndroidManifest.xml file of your project, you declare INTERNET permission and in the application tab, you define a meta-data tag with the name "com.facebook.sdk.ApplicationId" and the value "@string/facebook_app_id".

Then back to your app on https://developers.facebook.com, on the left menu bar, click settings. In the box under Google Play Package Name, you enter the package of your Android project (e.g. com.example.testfaceapp). Under Class Name, enter your main class (e.g. com.example.testfaceapp.MainActivity). Under Key Hashes, you have to enter a hash key of your project. The following code helps you get the hash key.

try {
        PackageInfo info = context.getPackageManager().getPackageInfo(
             "com.example.testfaceapp", PackageManager.GET_SIGNATURES); //Your        package name here
        for (Signature signature : info.signatures) {
           MessageDigest md = MessageDigest.getInstance("SHA");
           md.update(signature.toByteArray());
           Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
           }
     } catch (NameNotFoundException e) {
     } catch (NoSuchAlgorithmException e) {
     }


In your Android project, you create a class called LoginFragment that extends Fragment class of support-v4 library. In the layouts folder, you create a layout file called login.xml for the LoginFragment. In the layout file, you define a Facebook LoginButton.

<com.facebook.widget.LoginButton
     android:id="@+id/authButton"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="center_horizontal"
     android:layout_marginTop="30dp"
     />


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment{
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   View view = inflater.inflate(R.layout.login, container, false);
   return view;
}
public void onSaveInstanceState(Bundle outState) {
   super.onSaveInstanceState(outState);
   //uiHelper.onSaveInstanceState(outState);
}
}

In the onCreate() method of the MainActivity class, you write code to add the LoginFragment to the activity. And in the on onActivityResult() method, you will get a response code from Facebook. If the response code equals to RESULT_OK constant, it means the login is successful. So, you can do something. In my case, it opens another activity called WelcomeActivity. On that activity, there is a button to log out.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.facebook.AppEventsLogger;
import com.facebook.Session;
import android.support.v4.app.FragmentActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends FragmentActivity{

   LoginFragment mainFragment;
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
        // Add the fragment on initial activity setup
        mainFragment = new LoginFragment();
        getSupportFragmentManager()
        .beginTransaction()
        .add(android.R.id.content, mainFragment)
        .commit();
     } else {
        // Or set the fragment from restored state info
        loginFragment = (LoginFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
     }
   }
  
  
   @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if(resultCode==Activity.RESULT_OK){
   // Start another activity when the login is successful
   Intent intent=new Intent(this,WelcomeActivity.class);
   startActivity(intent);
  
  
   }
  
}

}


Here is the code written in the WelcomeActivity class to log out the user when pressing the Log out button. The Log out button is defined in activity_welcome.xml file.

public class WelcomeActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
Button logoutButton=(Button)findViewById(R.id.btlogout);
logoutButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Session session = Session.getActiveSession();
   // Closes the local in-memory Session object and clears any persistent
   // cache related to the Session.
   session.closeAndClearTokenInformation();
   // return the user to the login screen
   startActivity(new Intent(getApplicationContext(), MainActivity.class));
   // make sure the user can not access the page after he/she is logged out
   // clear the activity stack
   finish();
}

});
}
}
Facebook SDK requires you declare an activity called LoginActivity in the AndroidManifest.xml file. So, add the following lines to the file.
<activity
        android:name="com.facebook.LoginActivity"
        android:label="@string/title_facebook_login" >
</activity>


Android-facebook-login

Posted by: Dara | post date: 01-02-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.