Facebook webview called twice in Android app - facebook

I'm testing my app on a device where the Facebook application is not installed.
So when I'm logging with Facebook, a webview is opened.
The strange this is that when I've inserted my username and password, after pressing ok a webview is reopened and I've to insert the username and password again and I can login.
What could be ?
authButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
authButton.setVisibility(View.GONE);
logoutButton.setVisibility(View.VISIBLE);
// start Facebook Login
Session.openActiveSession(Login.this, true, new Session.StatusCallback() {
// callback when session changes state
SharedPreferences.Editor edit = pref.edit();
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
accesstoken = session.getAccessToken();
edit.putString("fbtoken", accesstoken);
if (session.getExpirationDate()!= null)
edit.putLong("com.facebook.sdk.AccessTokenExpires", session.getExpirationDate().getTime());
Log.d("FACEBOOK", "LOGGED IN");
}
});
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
Login.this, PERMISSIONS);
session.requestNewReadPermissions(newPermissionsRequest);
return;
}
// make request to the /me API
Request.newMeRequest(session, new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
Log.d("FACEBOOK", "onCompleted");
Log.d("",""+user);
try {
name=user.getName();
email=user.getProperty("email").toString();
location=(user.getLocation().getProperty("name").toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("ID", user.getId());
}
}).executeAsync();
}
}
});
}
});

I've had the same problem on iOS so this problem could be linked.
I solved it by removing the delegate after I received the first response.
So it may be applicable in your exemple like this:
Session.openActiveSession(Login.this, true, new Session.StatusCallback() {
// callback when session changes state
if (logoutButton.getVisibility() == View.VISIBLE) {
// Its visible so we end the callback
return;
}
SharedPreferences.Editor edit = pref.edit();

My guess is that you're saving the access token into the shared pref,
and it needs some time to be saved on disk if you don't force it.
You should add
edit.putLong("com.facebook.sdk.AccessTokenExpires", ...);
edit.commit(); // <- this line
so you are sure that for the next call it will be available

Related

Unity Authentication for Android - SignInWithGoogleAsync Throws Permission Denied

I'm sure I'm missing something silly but after I retrieve and pass the google id token to Unity Authentication I get the errors:
[Authentication]: Request failed: 401, {"title":"PERMISSION_DENIED","detail":"validation failed","details":[],"status":401}
WebRequestException: {"title":"PERMISSION_DENIED","detail":"validation failed","details":[],"status":401}
Below is my code, any help appreciated:
async void Awake()
{
await UnityServices.InitializeAsync();
InitializePlayGamesLogin();
}
void InitializePlayGamesLogin()
{
PlayGamesPlatform.Activate();
}
// Call when login button is pressed
public void LoginGooglePlayGames()
{
Social.localUser.Authenticate(OnGooglePlayGamesLogin);
}
//Check login success
async void OnGooglePlayGamesLogin(bool success)
{
if (success)
{
// Call Unity Authentication SDK to sign in or link with Google.
string idToken = PlayGamesPlatform.Instance.GetUserId();
await SignInWithGoogleAsync(idToken);
}
else
{
Debug.Log("Unsuccessful login");
}
}
async Task SignInWithGoogleAsync(string idToken)
{
try
{
await AuthenticationService.Instance.SignInWithGoogleAsync(idToken);
Debug.Log("SignIn is successful.");
//if sign in successful turn off login screen.
loginScreen.SetActive(false);
}
catch (AuthenticationException ex)
{
// Compare error code to AuthenticationErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
}

Why is there a delay between closing interstitial ad and opening the target activity?

I implemented this android code to load and show an interstitial ad and after closing the ad it will open the target activity, but my problem is there's a 3 seconds delay between closing and opening the target activity...here's my code:
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(HomeActivity.this, UNIT_ID, adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
admobInterstitialAd = interstitialAd;
admobInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
admobInterstitialAd = null;
/**********Here is the delay when starting the activity for about 3 seconds*******/
Intent intent = new Intent(HomeActivity.this, SettingsActivity.class);
startActivity(intent);
/********************************************************************************/
}
#Override
public void onAdFailedToShowFullScreenContent(com.google.android.gms.ads.AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
admobInterstitialAd = null;
Intent intent = new Intent(HomeActivity.this, SettingsActivity.class);
startActivity(intent);
}
#Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
admobInterstitialAd = null;
}
});
if (admobInterstitialAd != null) {
admobInterstitialAd.show(HomeActivity.this);
}
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
admobInterstitialAd = null;
Intent intent = new Intent(HomeActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
Any suggestions to fix this issue....thanks in advance...
I faced the same problem. I still haven't been able to fix the problem and couldn't find a resource that does. While searching on Google, I realized that you are not alone and those who have the same problem on other platforms.
As a workaround, I will use a progress dialog. This makes users wait until the ad closes and the new event starts. I think 1-3 seconds.
if (mInterstitialAd != null) {
mInterstitialAd.show(MainAct.this);
startActivity(new Intent(MainAct.this, NewAct.class));
progressDialog.show();
} else {
startActivity(new Intent(MainAct.this, MafA.class));
}

Can't login with facebook in Windows Phone App

It was working fine before but It's not working even though I haven't changed anything in my Facebook related code. It is giving this error:
App doesn't give permission to given URL : The settings of app doesn't allow one or more of the given URL's. URLs must be Website's URL or Canvas URL...
Here is my FacebookLoginPage.cs:
namespace MyApp.Pages
{
public partial class FacebookLoginPage : PhoneApplicationPage
{
private string message;
public FacebookLoginPage()
{
InitializeComponent();
message = String.Empty;
this.Loaded += FacebookLoginPage_Loaded;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
NavigationService.GoBack();
base.OnBackKeyPress(e);
}
private async void FacebookLoginPage_Loaded(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(App.AccessToken))
{
App.isAuthenticated = true;
await Authenticate();
}
}
private FacebookSession session;
private async Task Authenticate()
{
//Facebook logini kontroli eğer login olduysa AccessToken ve bilgileri çeker.
try
{
if (App.FacebookSessionClient.LoginInProgress == true && !String.IsNullOrEmpty(message))
{
App.FacebookSessionClient.LoginInProgress = false;
}
else
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
App.AccessToken = session.AccessToken;
App.appSettings["accessToken"] = App.AccessToken;
App.appSettings.Save();
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/MainPage.xaml?token=" + App.AccessToken, UriKind.Relative)));
}
}
catch (InvalidOperationException)
{
message = "failed";
App.FacebookSessionClient.LoginInProgress = true;
NavigationService.GoBack();
}
}
}
}
What might be the probelm?
When I added facebook.com to Oauth part of Advanced Setting in my Facebook App, the problem solved. Thanks to the following link: Windows Phone 8 Facebook Login Given URL is not allowed by the application

how to open facebook session in android

I am developing a simple app which login facebook .
I am trying to display the facebook profile name in the textview..
I am creating the app on facebook and also put appId into menifest .
In my app can not cause any error but it can't display the Facebook profile name into textview .
I found that the facebook session is not open thats why it can't connect to my bacebook account...
Here is my code :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
System.out.println("Session is open....");
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
TextView welcome = (TextView) findViewById(R.id.welcome);
if (user != null) {
welcome.setText("Hello " + user.getName() + "!");
System.out.println("Hello " + user.getName());
}
else {
welcome.setText("User not present");
}
}
});
}
else {
System.out.println("Session is not open....");
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}}
Can anybody tell mi how to connect to facebook session...
Thank u in advance.
The problem might be in key Hash.
You shud definitely see this tutorial:
https://developers.facebook.com/docs/android/getting-started
Look at the Troubleshooting section, that might help you

getting "FacebookAuthorizationException: User logged in as different Facebook user" exception - while updating to get new Permission

I am getting FacebookAuthorizationException: User logged in as different Facebook user , while trying to update permission to publish ,My code looks like below
onCreate(...) {
connectFacebookAccount();
}//oncreate
private void connectFacebookAccount() {
settings = getSharedPreferences("PREF_NAME",MODE_PRIVATE);
String FbExperi = settings.getString("FB_AccessExpires, null);
String accesstoken = settings.getString(FB_AccessToken, null);
if (accesstoken != null) {
// open a session from the access token info
// saved in the app's shared preferences
Date date = null;
try {
date = (Date) new SimpleDateFormat("MMMM d, yyyy",
Locale.ENGLISH).parse(FbExperi);
} catch (ParseException e) {
e.printStackTrace();
}
AccessToken accessToken = AccessToken
.createFromExistingAccessToken(accesstoken, date, null,
null, null);
Session.openActiveSessionWithAccessToken(NewTest.this, accessToken,
new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session != null && session.isOpened()) {
Session.setActiveSession(session);
getPublishPremission();
}
}
});
}
}
private void getPublishPremission(){
if (Session.getActiveSession().getPermissions() == null
|| !Session.getActiveSession().getPermissions()
.containsAll(PERMISSIONS)) {
Session.getActiveSession().requestNewPublishPermissions(
new Session.NewPermissionsRequest(
NewTest.this, PERMISSIONS));
}else{
publishFeedDialog()
}
private void publishFeedDialog() {
//open WebDialog to publish feed
}
The execution flow revolves around requestNewPublishPermissions and StatusCallback hence the permission is not set .I request your help to point out where i went wrong.I have an logged in using different facebook Id in my facebook app.In my app i am trying to log-in using different facebook Id from the access token info saved in the app's shared preferences.
see this link
There is a bug in facbook sdk,when there is no facebbok app installed on device.When user ask for additional permission,it takes user to the login dialog again.