1) Create New Facebook App:
https://developers.facebook.com/apps/
2) Add Facebook Id in AndoridManifest file:
if facebook app id is 123456 then put it as below, change it as per your app id.
<application>
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="123456" />
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProvider123456"
android:exported="true" />
</application>
3) Java Code (Get full code from here: https://goo.gl/ALHTzF)
public class MyActivity extends AppCompatActivity {
CallbackManager callbackManager;
Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
initUI();
}
private void initUI() {
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
if (loginResult.getAccessToken() != null) {
String strAccessToken = loginResult.getAccessToken().getToken();
Log.d("Token is", strAccessToken);
getProfile(loginResult.getAccessToken());
}
}
@Override
public void onCancel() {
showToast("Login Cancel");
}
@Override
public void onError(FacebookException exception) {
showToast(exception.getMessage());
}
});
btnLogin = (Button) findViewById(R.id.btnlogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(MyActivity.this, Arrays.asList("public_profile", "user_friends"));
}
});
}
public void getProfile(AccessToken accessToken) {
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
//retrive email and name from here...
Log.d("JSON OBJECT OF PROFILE", object.toString());
Log.v("GraphResponse : ", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (callbackManager.onActivityResult(requestCode, resultCode, data)) {
return;
}
}
}
4) You can use it in Fragment too.
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(MyFragment.this, Arrays.asList("public_profile", "user_friends"));
}
});