Android App Integrated Facebook Login

Source: Internet
Author: User
Tags openssl sha1 sha1

  Before is to do domestic application development, has not used foreign three-party login, such as Google login, Facebok login, recently participated in an overseas payment related projects, survey of Google Login and Facebook login, in fact, after the survey felt is also very simple,    In particular, Facebook login, with the domestic three-party login integration almost no difference. Let's talk about the Facebok login integration process: First you need to register a developer account on the Facebook developer website (if you have a Facebook account), URL: developers.facebook.com, the following is the official website of the page:  on the right side of the page has a My app, click on the drop-down menu to create your own app:   this click "Add New App", will pop up the following page, A fill in the app name, a fill in your own mailbox, and then click "Create app Number" to complete the action to create an app:    below is the background configuration page of the app that was created after the app was built, including the app's id:   "Add Product" on the left menu bar. tab, on the right of the feature selection inside choose Login This module, click Settings:   and then select android:   Select Android will go to the following page:   we will see the process is divided into 1 0 steps: The first step: Choose your own application, here our demo application is logindemo:   the second step: the official website gives the step is to download the "Facebook" app, actually do not download, they have their own web version login, this step can be skipped: & nbsp;  Step Three: You need to add a mavencentral () to the buildscript {repositories {}} in the Build.gradle below project, and the effect is as follows:  &    nbsp Then in the app under the Build.gradle inside the dependencies inside add a sentence: Compile ' com.facebook.android:facebook-login:[4,5) ', and then build the project, will automatically download the SDK that was introduced to Facebook; Fourth Step: Edit Manifest Checklist: ①: Open/app/src/main/res/valUes/strings.xml file; ②: Add the code shown below ③:<string name= "facebook_app_id" > The app you created on Facebook id</string> <str ing name= "Fb_login_protocol_scheme" > The app you created on Facebook Id</string>④: Open/app/manifest/androidmanifest.xml File, add the uses-permission element to the manifest file: <uses-permission android:name= "Android.permission.INTERNET"/>⑤: In Application element, add the following meta-data element, an activity element for Facebook, and an activity element and intent filter for the Chrome custom tab. Replace @string/appname with the name of your Facebook app: <meta-data android:name= "Com.facebook.sdk.ApplicationId" Android:va Lue= "@string/facebook_app_id"/> <activity android:name= "com.facebook.FacebookActivity" Android:configcha      Nges= "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>  Fifth Step: Associate the package name with the app's default class: Package Name: Fill in the Software's package name default activity class name: Fill in the Default activity class package name and class name &nbsp ;  Sixth: Provide development and publishing key hashing for your app: to ensure the authenticity of your app's interactions with Facebook, you must first provide us with an Android key hash in your development environment.      If your app is already published, you should also provide a publishing key hash. Generate a development key hash each Android development environment will have a unique development key hash. To generate a development key hash, on your MAC, run the following command: Keytool-exportcert-alias androiddebugkey-keystore ~/.android/debug.keystore | OpenSSL sha1-binary | OpenSSL base64 in Windows, run the following command: Keytool-exportcert-alias androiddebugkey-keystore%homepath%\.android\debu G.keystore | OpenSSL sha1-binary | OpenSSL base64 This command will generate a unique key hash of 28 characters for your development environment. Copy and paste it into the fields below.      For the development environment for everyone involved in application development, you must provide the development key hash separately. Generate a publishing key a hash Android app must be electronically signed with a publishing key before it can be uploaded to the store. To generate a publish key hashcolumn, run the following command within your MAC or Windows and replace your publishing key alias and KeyStore path: Keytool-exportcert-alias your_release_key_alias-keystore YOUR _release_key_path | OpenSSL sha1-binary | OpenSSL base64 This generates a 28-character string that you should copy and paste into the following fields. Also, see your Android documentation for information about app signatures.   Seventh step: Enable Single Sign-on, select Yes, and save:  -------------------------------------------------------configuration end--------- -------------------------------------------  Now that all the configuration items are complete, here's the code integration phase, which is the use of Facebook login in your app.   Facebook offers two ways to use it directly, a UI that provides a custom view of Loginbutton, a slightly modified style that can be used in your layout, and a simple way to use it.    The second way is to directly customize any form of the button to add listening, in the hall in the direct code to perform the Facebook login operation. Method One: Use Loginbutton: Add Loginbutton to the XML code this view:  <?xml version= "1.0" encoding= "Utf-8"?> <linearlayou T xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" Android:layout_ height= "match_parent" android:orientation= "vertical" > <com.facebook.login.widget.loginbutton androi D:iD= "@+id/login_button" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Androi D:layout_gravity= "Center_horizontal" android:layout_margintop= "30DP" android:layout_marginbottom= "30DP"/&gt    ; </LinearLayout>  its style is such that:  this is not logged in style, the style of the login is just copy into the word "Log out", click to complete the exit, which is the integration of XML code,        Here's how it's integrated in Java code: public class Mainactivity extends fragmentactivity {Callbackmanager callbackmanager;          @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);          Callbackmanager = CallbackManager.Factory.create ();          Loginbutton Loginbutton = (Loginbutton) View.findviewbyid (R.id.usersettings_fragment_login_button);            Loginbutton.registercallback (Callbackmanager, New facebookcallback<loginresult> () {@Override public void onsuccess (Loginresult loginresult) { toast.maketext (Getapplicationcontext (), "FAcebook Login Successful ", Toast.length_short). Show (); } @Override public void OnCancel () {Toast.maketext (Getapplicationcontext (), "Facebook Login            Toast.length_short). Show (); } @Override public void OnError (facebookexception error) {Toast.maketext (getapplicatio            Ncontext (), "Facebook login Error", Toast.length_short). Show ();        }          });    Finally, call Callbackmanager.onactivityresult and pass the login results to Loginmanager through Callbackmanager. @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult (R      Equestcode, ResultCode, data);    Callbackmanager.onactivityresult (Requestcode, ResultCode, data); }  mode two: Use your own defined interface:  add any one button:  <?xml version= "1.0" encoding= "Utf-8" in the XML code?> <line Arlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" Android: Layout_height= "match_parent" android:gravity= "center" android:orientation= "vertical" >  <button         Android:id= "@+id/facebook_login" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "Facebook Login"/>  </LinearLayout>  add a button listener to the Java code and provide a login operation in the Listener:  mfacebookl Ogin.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {Loginmanager      . getinstance (). Loginwithreadpermissions (Mainactivity.this, Arrays.aslist ("Public_profile")); }});  also register a listener: Loginmanager.getinstance (). RegisterCallback (Callbackmanager, New Facebookcallback<loginr Esult> () {@Override public void onsuccess (Loginresult loginresult) {Toast.maketext (Getapplicationcon      Text (), "Facebook login Successful", Toast.length_short). Show (); }  @Override public void OnCancel () {Toast.maketext (Getapplicationcontext (), "Facebook login canceled", Toast.length_short). Show (); }  @Override public void OnError (facebookexception error) {Toast.maketext (Getapplicationcontext (),      "Facebook Login Error", Toast.length_short). Show (); }});  the benefit of this approach is that it retains its own UI style and does not create conflicting UI designs.   Here are the two ways to sign in   actually introduced to this is not the end, because we also want to get Facebook users of personal public information, but also to determine whether to login, so, some of the details of the end of the work to deal with: Facebook provides a    A listener, used to monitor the user's personal information changes, this listener is called Profiletracker, we can: Create a Profiletracker object: Private Profiletracker Profiletracker; Profiletracker = new Profiletracker () {@Override protected void oncurrentprofilechanged (profile oldprof Ile, Profile CurrentProfile) {//APP code  if (currentprofile! = null) {Toast.maketext (        Getapplicationcontext (), "personal information =" + Currentprofile.getfirstname (), Toast.length_short). Show (); } }};  Here the personal information is divided into Oldprofile and currentprofile, but this listening time to pay attention, because it will trigger this method login and exit, so to do the flight non-null judgment, and can be used to record whether the login and other lines For.   Well, write it down, I hope this article to everyoneHelpful.   If you want to reprint, please indicate the source, thank you!   Welcome to my Jane Book blog, address is:   http://www.jianshu.com/u/da06e00edefa   Welcome to my public attention, I will regularly publish some blogs, share some knowledge Knowledge points.    

Android App Integrated Facebook Login

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.