Currently this is how my FB login looks like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
TAG = "Login.Activity";
//Callback manager manages callbacks into the FB SDK from an Activity's onActivityResult() Method.
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
//If login in successful,
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
goMainScreen(profile);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(),R.string.cancel_login, Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), R.string.error_login, Toast.LENGTH_LONG).show();
}
});
}
private void goMainScreen(Profile profile) {
if(profile != null){
//Passing in the name,id and photo from the profile.
Intent intent = new Intent(this, MainActivity.class);
// intent.putExtra("name",profile.getName());
intent.putExtra("id",profile.getId());
intent.putExtra("photo",profile.getProfilePictureUri(200,200));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
//All Request Code, Result Code, and data are recieved by the activity
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
callbackManager.onActivityResult(requestCode,resultCode,data);
}
}
I would like to keep track of the user session throughout other activities and know if they have logged in before.Would I use sharedpreferences for this? If so will I be doing this at the beginning of the loginActivity?
Well you could use what provide the SDK and create a method like this one :
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
Related
I am developing an app that can share an image to Facebook.
Only I can share image, other people cannot share. I have a FAB and calling this activity on its onClick() method. I really don't know what to do, my app is live but when I click on my app name over the shared photo I get
"Misconfigured App
Sorry, MyApp hasn't been approved for display in App Centre."
What is the reason that others cannot share images? I really need the answer. Thanks.
public class ShareActivity extends AppCompatActivity {
private CallbackManager callbackManager;
private LoginManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions");
//this loginManager helps you eliminate adding a LoginButton to your UI
manager = LoginManager.getInstance();
manager.logInWithPublishPermissions(this, permissionNeeds);
manager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
sharePhotoToFacebook();
Toast.makeText(ShareActivity.this, "Success", Toast.LENGTH_LONG).show();
finish();
}
#Override
public void onCancel() {
Toast.makeText(ShareActivity.this, "Cancel", Toast.LENGTH_LONG).show();
finish();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(ShareActivity.this, "Error", Toast.LENGTH_LONG).show();
finish();
}
});
}
}
private void sharePhotoToFacebook(){
try {
URL url = new URL("http://burakakyalcin.site/image.png");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.setCaption("Hello")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
} catch(IOException e) {
System.out.println(e);
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data)
{
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}
}
I was reading the thread: Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User and I'm using exactly the same code to call a facebook login, but, is always firing the method onCancel, what I'm doing wrong?
public class LoginActivity extends AppCompatActivity {
CoordinatorLayout BackgroundImage;
int[] images = new int[] {R.drawable.bg01, R.drawable.bg02, R.drawable.bg03};
Button BtnIniciar;
TextView BtnRecuperar;
EditText txtCorreo;
EditText txtContrasena;
String androidId;
TextView btnRegistrar;
LoginButton loginButton;
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
BackgroundImage = (CoordinatorLayout)findViewById(R.id.background);
int imageId = (int)(Math.random() * images.length);
BackgroundImage.setBackgroundResource(images[imageId]);
BtnIniciar = (Button) findViewById(R.id.Iniciar);
BtnRecuperar = (TextView) findViewById(R.id.btnRecuperar);
txtCorreo = (EditText) findViewById(R.id.txtCorreo);
txtContrasena = (EditText) findViewById(R.id.txtContrasena);
btnRegistrar = (TextView) findViewById(R.id.btnRegistrar );
androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
Boolean isLogged = new HttpGetPost().IsLogged(androidId);
if(isLogged){
Intent intent = new Intent( LoginActivity.this, MainActivity.class);
startActivity(intent);
}
BtnIniciar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean result = new HttpGetPost().Login(txtCorreo.getText().toString(), txtContrasena.getText().toString(), 2, androidId);
if (result) {
Intent intent = new Intent(v.getContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(v.getContext(), "El usuario/contraseña no es válido.", Toast.LENGTH_LONG).show();
}
}
});
BtnRecuperar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RecuperarContrasena.class);
startActivity(intent);
}
});
btnRegistrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegistroActivity.class);
startActivity(intent);
}
});
//MultiDex.install(this);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends"));
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", response.toString());
// Application code
// String email = object.getString("email");
// String birthday = object.getString("birthday"); // 01/31/1980 format
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
return;
}
I found the error, the error was:
I was adding the key_hash into the fb_login_protocol_scheme and should be: fb12322222 because my APP ID is 12322222.
I've integrated facebook sdk v-4 with my android app. Here I've worked facebook login in 2 activities.
1) In one activity fb login is done via LoginButton. Where after successful login the fb login dialog is dismissed by facebook sdk automatically.
code:
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
ProfileTracker profileTracker;
#Override
public void onSuccess(LoginResult loginResult) {
Logger.d("FBLOGIN", "login successful. User ID: "
+ loginResult.getAccessToken().getUserId()
+ "\n" +
"Auth Token: "
+ loginResult.getAccessToken().getToken());
com.facebook.Profile fbProfile = com.facebook.Profile.getCurrentProfile();
if (fbProfile == null) {
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(com.facebook.Profile oldProfile, com.facebook.Profile currentProfile) {
profileTracker.stopTracking();
doTaskWithFbProfile(currentProfile);
}
};
profileTracker.startTracking();
} else {
doTaskWithFbProfile(fbProfile);
}
}
#Override
public void onCancel() {
Logger.d(TAG, "fb Login attempt canceled.");
}
#Override
public void onError(FacebookException e) {
Logger.e(TAG, "fb Login attempt failed." + e);
Toast.makeText(LoginActivity.this,R.string.str_please_check_your_internet_connection,Toast.LENGTH_LONG).show();
}
});
private void doTaskWithFbProfile(com.facebook.Profile fbProfile) {
Logger.d("FBLOGIN", "id - " + fbProfile.getId());
Logger.d("FBLOGIN", "name - " + fbProfile.getName());
Logger.d("FBLOGIN", "pic - " + fbProfile.getProfilePictureUri(150, 150));
com.android.circlecare.models.common.Profile profile = new com.android.circlecare.models.common.Profile();
profile.setFBID(fbProfile.getId());
profile.setName(fbProfile.getName());
profile.setProfilePhoto(fbProfile.getProfilePictureUri(150, 150).toString());
Intent intent = new Intent(this, LoginWithFacebookActivity.class);
intent.putExtra(LoginWithFacebookActivity.EXTRA_PROFILE, profile);
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
2)On the other hand I used LoginManager to log in to fb. Where after successful login the login dialog does not get dismissed, instead it stays in front and again after login the dialog doesn't go.
code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
mFacebookCallback = new FacebookCallback<LoginResult>() {
ProfileTracker profileTracker;
#Override
public void onSuccess(LoginResult loginResult) {
Profile fbProfile = Profile.getCurrentProfile();
if (fbProfile == null) {
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
profileTracker.stopTracking();
getAllFriends();
}
};
profileTracker.startTracking();
} else {
getAllFriends();
}
}
#Override
public void onCancel() {
Logger.d(TAG, "fb Login attempt canceled.");
}
#Override
public void onError(FacebookException error) {
Logger.d(TAG, "Error : " + error.getMessage());
finish();
}
};
callbackManager = CallbackManager.Factory.create();
if (hasAccess)
getAllFriends();
else
loginWorks();
}
private void loginWorks() {
loginManager = LoginManager.getInstance();
loginManager.registerCallback(callbackManager, mFacebookCallback);
ArrayList<String> publishPermission = new ArrayList<>();
publishPermission.add("publish_pages");
publishPermission.add("publish_actions");
loginManager.logInWithPublishPermissions(this, publishPermission);
ArrayList<String> readPermission = new ArrayList<>();
readPermission.add("user_friends");
readPermission.add("public_profile");
readPermission.add("user_about_me");
loginManager.logInWithReadPermissions(this, readPermission);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
I've used almost same codes in both the cases, but I wonder why login dialog isn't get dismissed when working with LoginManager.
Can any one point out the problem or is there any api to dismiss fb login dialog(web view).
In your loginWorks() method, you're literally calling login twice, which is probably actually showing 2 different login screens, and why it looks like the dialog is not dismissing after you finish one of them. Try removing the loginWithPublishPermissions call, and put it in the callback from the read permissions call if you really need it.
I'm having trouble authenticating users with Facebook and creating a single new identity with AWS Cognito. Then if that user deletes the app and re-downloads it I want Cognito to return the same identity.
Facebook login works but credentialsProvider.setLogins(logins); creates 4 NEW unauthenticated identities every time.
final CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(getApplicationContext(), "xxxxxxxx", Regions.US_EAST_1);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email", "user_friends"));
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
updateWithToken(currentAccessToken);
}
};
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Map<String, String> logins = new HashMap<String, String>();
logins.put("graph.facebook.com", AccessToken.getCurrentAccessToken().getToken());
credentialsProvider.setLogins(logins);
Log.d("LogTag", "my ID is " + logins);
}
#Override
public void onCancel() {
Toast.makeText(getBaseContext(), "Login Cancelled", Toast.LENGTH_SHORT).show();
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
Toast.makeText(getBaseContext(), "Problem connecting to Facebook", Toast.LENGTH_SHORT).show();
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
private void updateWithToken(AccessToken token) {
if (token != null) {
Intent intent = new Intent(LogIn.this, NavDrawer.class);
LogIn.this.startActivity(intent);
}
;
}
#Override
public void onDestroy() {
super.onDestroy();
accessTokenTracker.stopTracking();
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
updateWithToken(AccessToken.getCurrentAccessToken());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
Intent intent = new Intent(LogIn.this, Buffer.class);
LogIn.this.startActivity(intent);
}
}
Any help would be amazing, thanks you!
I can see you are starting a new activity every time your access token from Facebook is updated. That mean you are creating different instances of CognitoCachingCredentialsProvider every time, which is not right.
Ideally you should have CognitoCachingCredentialsProvider as a singleton in your application and use is in all you activities and app logic. You can use the Cognito sample application as an example to model the flow.
This is my first post, so please let me know if I'm not abiding by the community rules.
Now to the problem! I've been trying to setup the Facebook login process for an app and I've gotten as far as adding a GUI element (the built-in Facebook login button), and having the button go ahead and ask for a user/pass, granting the app access to the user's account. The problem I'm facing is that when using the following code to get a callback value from the app I receive nothing (no value being printed). Right now I'm printing to LogCat arbitrary values, however as soon as printing works, I look to access the user access_token and other information (which didn't initially work). Any help appreciated!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect_accounts);
Log.i("fromMe", "test1");
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>(){
public void onSuccess(LoginResult loginResult) {
Log.i("fromMe", "1");
}
public void onCancel() {
Log.i("fromMe", "2");
}
public void onError(FacebookException exception) {
Log.i("fromMe", "3");
}
});
}
if Log.i("fromMe", "1");work so you can call :
AccessToken accessToken = loginResult.getAccessToken();
in your onSuccess().
And in onActivityResult(int requestCode, int resultCode, Intent data)
add :
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
I never used the built-in facebook button ,instead i used the normal button with a click a listener. and i call this method in the onClick().
myButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Starting facebook signIN
startFbSignIn();
}
});
startFbSignIn();
private void startFbSignIn() {
List<String> permissions = new ArrayList<>();
permissions.add("email");
Session.openActiveSession(this, true, permissions, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState sessionState, Exception e) {
Log.d("X", "Call Called");
if (session.isOpened()) {
Log.d("X", "SessionOpened" + session.getAccessToken());
//Showing some loading
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser graphUser, Response response) {
//FACEBOOOK SIGNIN SUCCESS
Log.i("X", "Facebook Login Success");
//Log
Log.d("X", "GRAPH USER:" + graphUser.toString());
String name = graphUser.getName();
//.....
}
}).executeAsync();
} else {
Log.d("X", "SessioNOTopened");
}
}
});
}
The above method successfully working for me and your onActivityResult() must look something like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Facebook Session Manager
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
Probably cause of a bug in the facebook SDK you cannot directly get the accessToken. We need to create an accessToken tracker and then get the accessToken
private AccessTokenTracker accessTokenTracker;
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
try {
if (newAccessToken.getToken() != null) {
facebookAccessToken = newAccessToken.getToken();
//this is your accessToken here
}
else if (oldAccessToken.getToken() != null) {
facebookAccessToken = oldAccessToken.getToken();
//this is your accessToken here
}else {
Toast.makeText(getBaseContext(), "Facebook Login Failed", Toast.LENGTH_LONG).show();
}
if(oldAccessToken.getToken()!=null)
Log.e("old", oldAccessToken.getToken());
}catch (Exception e){
e.printStackTrace();
}
}
};
once this is successfully done, overide the onStop method of the activity and make sure you stoptracking the accessToken there.
accessTokenTracker.stopTracking();