using facebook sdk in Android studio

2018-12-31 18:13发布

问题:

I\'m following Facebook SDK for Android using Android Studio. When I run my application I\'m getting the below mentioned warning.

Gradle: module \'facebook\' won\'t be compiled. Unfortunately you can\'t have non-Gradle Java module and Android-Gradle module in one project.

How should I solve this?

I tried @Scott Barta\'s answer and get the following error message.

    A problem occurred configuring project \':App\'.
> Failed to notify project evaluation listener.
   > A problem occurred configuring project \':libraries:facebook\'.
      > Failed to notify project evaluation listener.
         > Could not resolve all dependencies for configuration \':libraries:facebook:_DebugCompile\'.
            > Could not find any version that matches com.android.support:support-v4:+.
              Required by:
                  MyApplication2.libraries:facebook:unspecified

回答1:

NOTE

For Android Studio 0.5.5 and later, and with later versions of the Facebook SDK, this process is much simpler than what is documented below (which was written for earlier versions of both). If you\'re running the latest, all you need to do is this:

  1. Download the Facebook SDK from https://developers.facebook.com/docs/android/
  2. Unzip the archive
  3. In Android Studio 0.5.5 or later, choose \"Import Module\" from the File menu.
  4. In the wizard, set the source path of the module to import as the \"facebook\" directory inside the unpacked archive. (Note: If you choose the entire parent folder, it will bring in not only the library itself, but also all of the sample apps, each as a separate module. This may work but probably isn\'t what you want).
  5. Open project structure by Ctrl + Shift + Alt + S and then select dependencies tab. Click on + button and select Module Dependency. In the new window pop up select :facebook.
  6. You should be good to go.

Instructions for older Android Studio and older Facebook SDK

This applies to Android Studio 0.5.4 and earlier, and makes the most sense for versions of the Facebook SDK before Facebook offered Gradle build files for the distribution. I don\'t know in which version of the SDK they made that change.

Facebook\'s instructions under \"Import the SDK into an Android Studio Project\" on their https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android-using-android-studio/3.0/ page are wrong for Gradle-based projects (i.e. your project was built using Android Studio\'s New Project wizard and/or has a build.gradle file for your application module). Follow these instructions instead:

  1. Create a libraries folder underneath your project\'s main directory. For example, if your project is HelloWorldProject, you would create a HelloWorldProject/libraries folder.

  2. Now copy the entire facebook directory from the SDK installation into the libraries folder you just created.

  3. Delete the libs folder in the facebook directory. If you like, delete the project.properties, build.xml, .classpath, and .project. files as well. You don\'t need them.

  4. Create a build.gradle file in the facebook directory with the following contents:

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath \'com.android.tools.build:gradle:0.6.+\'
        }
    }
    
    apply plugin: \'android-library\'
    
    dependencies {
        compile \'com.android.support:support-v4:+\'
    }
    
    android {
        compileSdkVersion 17
        buildToolsVersion \"19.0.0\"
    
        defaultConfig {
            minSdkVersion 7
            targetSdkVersion 16
        }
    
        sourceSets {
            main {
                manifest.srcFile \'AndroidManifest.xml\'
                java.srcDirs = [\'src\']
                resources.srcDirs = [\'src\']
                res.srcDirs = [\'res\']
            }
        }
    }
    

    Note that depending on when you\'re following these instructions compared to when this is written, you may need to adjust the classpath \'com.android.tools.build:gradle:0.6.+\' line to reference a newer version of the Gradle plugin. Soon we will require version 0.7 or later. Try it out, and if you get an error that a newer version of the Gradle plugin is required, that\'s the line you have to edit.

  5. Make sure the Android Support Library in your SDK manager is installed.

  6. Edit your settings.gradle file in your application’s main directory and add this line:

    include \':libraries:facebook\'
    
  7. If your project is already open in Android Studio, click the \"Sync Project with Gradle Files\" button in the toolbar. Once it\'s done, the facebook module should appear. \"enter

  8. Open the Project Structure dialog. Choose Modules from the left-hand list, click on your application’s module, click on the Dependencies tab, and click on the + button to add a new dependency. \"enter
  9. Choose “Module dependency”. It will bring up a dialog with a list of modules to choose from; select “:libraries:facebook”. \"enter
  10. Click OK on all the dialogs. Android Studio will automatically resynchronize your project (making it unnecessary to click that \"Sync Project with Gradle Files\" button again) and pick up the new dependency. You should be good to go.


回答2:

Facebook has indeed added the SDK to the Maven Central repositories. To configure your project using the maven repo\'s instance, you\'ll need to do 2 things:

  1. In your projects top-level build.gradle file, add the Maven Central repositories. Mine looks like this:

    repositories {
        jcenter()       // This is the default repo
        mavenCentral()  //  This is the Maven Central repo
    }
    
  2. In the app-level build.grade file, add the Facebook sdk dependency:

    dependencies {
    
        compile \'com.facebook.android:facebook-android-sdk:4.5.0\' // Adjust the version accordingly
        // All your other dependencies.
    }
    

You can also adjust the specific Facebook SDK version as well. For a list of available versions in the maven repository click this link.



回答3:

Facebook publishes the SDK on maven central :

Just add :

repositories {
    jcenter()       // IntelliJ main repo.
}

dependencies {
    compile \'com.facebook.android:facebook-android-sdk:+\'
}


回答4:

Scott Barta\'s solution worked for me, except I had to add these to the dependencies of my main project build.gradle file:

compile files(\'libs/android-support-v4.jar\')
compile project(\':libraries:facebook\')

Also worth mentioning, you need to make sure:

android {
    compileSdkVersion 18
    buildToolsVersion \"18.1.1\"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 18
    }

Are the same in both build.gradle files...Once i did this it ran like a charm.



回答5:

When using git you can incorporate the newest facebook-android-sdk with ease.

  • Add facebook-android-sdk as submodule: git submodule add https://github.com/facebook/facebook-android-sdk.git
  • Add sdk as gradle project: edit settings.gradle and add line: include \':facebook-android-sdk:facebook\'
  • Add sdk as dependency to module: edit build.gradle and add within dependencies block: compile project(\':facebook-android-sdk:facebook\')


回答6:

I have used facebook sdk 4.10.0 to integrate login in my android app. Tutorial I followed is :

facebook login android studio

You will be able to get first name, last name, email, gender , facebook id and birth date from facebbok.

Above tutorial also explains how to create app in facebook developer console through video.

add below in build.gradle(Module:app) file:

repositories {
        mavenCentral()
    }

and

 compile \'com.facebook.android:facebook-android-sdk:4.10.0\'

now add below in AndroidManifest.xml file :

 <meta-data android:name=\"com.facebook.sdk.ApplicationId\" android:value=\"your app id from facebook developer console\"/>

     <activity android:name=\"com.facebook.FacebookActivity\"
               android:configChanges=\"keyboard|keyboardHidden|screenLayout|screenSize|orientation\"
               android:theme=\"@android:style/Theme.Translucent.NoTitleBar\"
               android:label=\"@string/app_name\" />

add following in activity_main.xml file :

<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"
    xmlns:tools=\"http://schemas.android.com/tools\"
    android:layout_width=\"match_parent\"
    android:layout_height=\"match_parent\"
    android:orientation=\"vertical\"
    tools:context=\"com.demonuts.fblogin.MainActivity\">

    <TextView
        android:layout_width=\"wrap_content\"
        android:layout_height=\"wrap_content\"
        android:textColor=\"#000\"
        android:layout_marginLeft=\"10dp\"
        android:textAppearance=\"?android:attr/textAppearanceMedium\"
        android:id=\"@+id/text\"/>

    <com.facebook.login.widget.LoginButton
        android:id=\"@+id/btnfb\"
        android:layout_gravity=\"center_horizontal\"
        android:layout_marginTop=\"10dp\"
        android:layout_width=\"wrap_content\"
        android:layout_height=\"wrap_content\" />

</LinearLayout>

And in last add below in MainActivity.java file :

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;


public class MainActivity extends AppCompatActivity {

    private TextView tvdetails;
    private CallbackManager callbackManager;
    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;
    private LoginButton loginButton;
    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v(\"LoginActivity\", response.toString());

                            // Application code
                            try {
                                Log.d(\"tttttt\",object.getString(\"id\"));
                                String birthday=\"\";
                                if(object.has(\"birthday\")){
                                    birthday = object.getString(\"birthday\"); // 01/31/1980 format
                                }

                                String fnm = object.getString(\"first_name\");
                                String lnm = object.getString(\"last_name\");
                                String mail = object.getString(\"email\");
                                String gender = object.getString(\"gender\");
                                String fid = object.getString(\"id\");
                                tvdetails.setText(fnm+\" \"+lnm+\" \\n\"+mail+\" \\n\"+gender+\" \\n\"+fid+\" \\n\"+birthday);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });
            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() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(this);
        setContentView(R.layout.activity_main);

        tvdetails = (TextView) findViewById(R.id.text);

        loginButton = (LoginButton) findViewById(R.id.btnfb);

        callbackManager = CallbackManager.Factory.create();

        accessTokenTracker= new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {

            }
        };

        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {

            }
        };

        accessTokenTracker.startTracking();
        profileTracker.startTracking();
        loginButton.setReadPermissions(Arrays.asList(\"public_profile\", \"email\", \"user_birthday\", \"user_friends\"));
        loginButton.registerCallback(callbackManager, callback);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onStop() {
        super.onStop();
        accessTokenTracker.stopTracking();
        profileTracker.stopTracking();
    }

    @Override
    public void onResume() {
        super.onResume();
        Profile profile = Profile.getCurrentProfile();

    }

}


回答7:

I deployed Facebook Android SDK to Sonatype repository.

You can include this library as Gradle dependency:

repositories {
    maven {
        url \'https://oss.sonatype.org/content/groups/public\'
    }
}

dependencies {
    compile \'com.shamanland:facebook-android-sdk:3.15.0-SNAPSHOT\'
}

Original post here.



回答8:

People using Android Studio 0.8.6 could do these:

  1. Download Facebook-android-sdk-xxx.zip & Unzip it
  2. Copy ONLY facebook dir under the Facebook-android-sdk-xxx dir into your project along with app/

    • ImAnApp/
      • |-- app/
      • |-- build/
      • |-- facebook/
  3. Now you should see Android Studio showing facebook as module

  4. Modify the build.gradle of facebook into this.
    • provided files(\'../libs/bolts.jar\') to provided files(\'./libs/bolts.jar\')
    • compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) to compileSdkVersion 20 or other version you defined in the app
    • buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION to buildToolsVersion \'20.0.0\'
    • minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) to minSdkVersion 14
    • targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) to targetSdkVersion 20

    apply plugin: \'android-library\'

    dependencies {
        compile \'com.android.support:support-v4:19.1.+\'
        provided files(\'./libs/bolts.jar\')
    }

    android {
        compileSdkVersion 20
        buildToolsVersion \'20.0.0\'

        defaultConfig {
            minSdkVersion 14
            targetSdkVersion 20
        }

        lintOptions {
            abortOnError false
        }

        sourceSets {
            main {
                manifest.srcFile \'AndroidManifest.xml\'
                java.srcDirs = [\'src\']
                res.srcDirs = [\'res\']
            }
        }
    }

Resync your gradle file & it should just work fine!



回答9:

I fixed the

\"Could not find property \'ANDROID_BUILD_SDK_VERSION\' on project \':facebook\'.\"

error on the build.gradle file, by adding in gradle.properties the values:

ANDROID_BUILD_TARGET_SDK_VERSION=21<br>
ANDROID_BUILD_MIN_SDK_VERSION=15<br>
ANDROID_BUILD_TOOLS_VERSION=21.1.2<br>
ANDROID_BUILD_SDK_VERSION=21<br>

Source: https://stackoverflow.com/a/21490651/2161698



回答10:

Create build.gradle file in facebook sdk project:

apply plugin: \'android-library\'

dependencies {
    compile \'com.android.support:support-v4:18.0.+\'
}

android {
    compileSdkVersion 8
    buildToolsVersion \"19.0.0\"

    sourceSets {
        main {
            manifest.srcFile \'AndroidManifest.xml\'
            java.srcDirs = [\'src\']
            resources.srcDirs = [\'src\']
            res.srcDirs = [\'res\']
            assets.srcDirs = [\'assets\']
        }

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot(\'build-types/debug\')
        release.setRoot(\'build-types/release\')
    }
}

Then add include \':libs:facebook\' equals <project_directory>/libs/facebook (path to library) in settings.gradle.



回答11:

*Gradle Repository for the Facebook SDK.

dependencies {
    compile \'com.facebook.android:facebook-android-sdk:4.4.0\'
}

Search for the latest version facebook sdk



回答12:

using facebook sdk in android studio is quite simple , just add the following line in your gradle

  compile \'com.facebook.android:facebook-android-sdk:[4,5)\'

and make sure that you have updated Android support repository , if not then update it using stand alone sdk manger