I am able to log in and do export/import from my Android app using the v2 Dropbox API. The only problem is on first run when a token is requested and the Dropbox app/website is launched - I have to run Auth.startOAuth2Authentication at least twice with a pause in between to be able to read the token with Auth.getOAuth2Token.
Is there anyway to wait() and get notified when startOAuth2Authentication returns after acquiring a token?
Auth.startOAuth2Authentication(this, getString(R.string.app_key));
//wait for response, retry, or time out and finish
String accessToken = Auth.getOAuth2Token();
prefs.edit().putString(ACCESS_TOKEN, accessToken).commit();
You shouldn't call startOAuth2Authentication twice, and you shouldn't call getOAuth2Token immediately after calling startOAuth2Authentication.
You should start the flow by calling startOAuth2Authentication as shown in the example here:
https://github.com/dropbox/dropbox-sdk-java/blob/master/examples/android/src/main/java/com/dropbox/core/examples/android/UserActivity.java#L36
And then you should complete the flow by calling getOAuth2Token later in onResume as shown in the example here:
https://github.com/dropbox/dropbox-sdk-java/blob/master/examples/android/src/main/java/com/dropbox/core/examples/android/DropboxActivity.java#L22
Here is a simple example for implementing the Dropbox Android API:
https://www.sitepoint.com/adding-the-dropbox-api-to-an-android-app/
Now, to get to the point of your question, you will not be able to get a toke immediately after Auth.startOAuth2Authentication(this, getString(R.string.app_key)); is called. After you call this method, the Dropbox login activity is shown, and you can get the token only after the user logs in (which is in no way immediate, and you have no way of telling how long it will take).
After the user logs in successfully your activity will be resumed, and you can see in the example from the tutorial that the Activity's onResume method is overridden a check is performed in there.
I will copy below the LoginActivity from this tutorial. It should be easy enough to start from here:
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button SignInButton = (Button) findViewById(R.id.sign_in_button);
SignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Auth.startOAuth2Authentication(getApplicationContext(), getString(R.string.APP_KEY));
}
});
}
#Override
protected void onResume() {
super.onResume();
getAccessToken();
}
public void getAccessToken() {
String accessToken = Auth.getOAuth2Token(); //generate Access Token
if (accessToken != null) {
//Store accessToken in SharedPreferences
SharedPreferences prefs = getSharedPreferences("com.example.valdio.dropboxintegration", Context.MODE_PRIVATE);
prefs.edit().putString("access-token", accessToken).apply();
//Proceed to MainActivity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
}
Related
Code of my splash screen:
public class SplashScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Thread thread = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(SplashScreen.this, FirstSlider.class);
startActivity(intent);
finish();
}
}
};
thread.start();
}
}
I want to move directly to my mainActivity if user already exist.
I'm using phone number to to sign in user in firebase android ,how can i keep user signed in until user sign out?
This is actually the default behavior of Firebase Authentication: it persists the user credentials and restores them when the app restarts.
So by the time your main activity executes the FirebaseAuth.getInstance().getCurrentUser() should already be returning the restored user account. If that is not happening, consider listening to the authentication state to ensure your code executes after the user is restored.
If neither of these is working for you, edit your question to show the relevant code - as none of the code you shared now seems to call Firebase in any way.
I have implemented login using finger print authentication and it works well.
Below is the Activity that calls the authenticate method:
FingerPrintActivity
onCreate(){
… //Code to initialize the fingerprint manager
FingerprintHandler fingerprintHandler = new FingerprintHandler(this);
fingerprintHandler.startAuthentication(fingerprintManagerCompat, null);
}
FingerPrintHandler
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
updateLoginUi("Successfully verified!", true);
}
private void updateLoginUi(String authenticationMessage, boolean result){
if(result){
context.startActivity(…)
}
}
After successfully verifying the fingerprint, I launch the MainActivity,
however, on pressing the back button to go back to the fingerprint activity, I am unable to use the service. What do I need to activate or trigger in order to validate the fingerprint again?
You could move
FingerprintHandler fingerprintHandler = new FingerprintHandler(this);
fingerprintHandler.startAuthentication(fingerprintManagerCompat, null);
from onCreate() to onResume().
In this case it would start authentication everytime you go into the activity, if that is what you want.
I am creating an app on Android that uses Firebase as database and Batch for pushing notifications. Usually, when my app starts, it goes to the main page, a login activity. The activity verifies if a user is still logged in using:
Firebase dbRef = new Firebase(Constants.URL_DB);
AuthData auth = dbRef.getAuth();
if (auth != null) // Proceed with a logged in user
else // Show authentication layout
My problem is that when I get a notification from Batch, I click on the notification to go to the app but then I am not logged in as I should be... auth == null. I don't want my users to need to log in every time they get a push from Batch. Can I detect that the app started from a notification? How is that I lose authentication from Firebase?
Here is the onCreate and onResume of the MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initiating Batch
Batch.onStart(this);
// Initiating layout
setContentView(R.layout.login);
// Setting database
Firebase.setAndroidContext(this);
// Unrelated stuff done here (Setting Views, etc)
}
#Override
protected void onResume() {
super.onResume();
// Getting login information from previous authentication.
Firebase dbRef = new Firebase(Constants.URL_DB);
AuthData auth = dbRef.getAuth();
// I added the addAuthStateListener here
if (auth != null) {
goToHomePage();
}
}
All right I found the problem. When I click on the notification, my MainActivity is called obviously. The thing is that when the user is logged in successfully, I start another Activity using:
startActivityForResult(intent, Constants.SUCCESS);
Now, onActivityResult is normally called to log out the user when the back button has been pressed on the home page. Otherwise, onResume is called and since the user is logged in, I would go straight back to the home page. BUT: when I click on a notification, somehow onActivityResult is called (probably because the activity stack gets trashed) and the user is logged out before resuming the activity.
So the solution is to log out the user in the onBackPressed of the home page activity. Then I don't need to startActivityForResult anymore.
// In the home page activity
#Override
public void onBackPressed() {
super.onBackPressed();
Firebase dbRef = new Firebase(Constants.URL_DB);
dbRef.unauth();
finish();
}
I post here because I've got a problem.
I'm working on a new android application , and I want to know how I can detect when a user is disconnecting (facebook logout button), because I want to refresh my UI at this moment.
I have been watched the official documentation, but I found nothing.
You can set a listener on the onCreate() method on your activity
AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null){
//User logged out
}
}
};
You need to import com.facebook.AccessToken and com.facebook.AccessTokenTracker
When you create the instance of AccessTokenTracker it implicitly starts tracking. For stopping tracking you should call AccessTokenTracker.stopTracking() e.g. in onDestroy() to not receive anymore events when not needed/wanted and especially to not leak memory!
You can get any time if the user is logged in/out by calling
AccessToken at = AccessToken.getCurrentAccessToken();
If the user is not logged in, you get a null value.
For further reference please check the documentation at https://developers.facebook.com/docs/reference/android/current/class/AccessTokenTracker/
You can try this also
if(AccessToken.getCurrentAccessToken()!=null)
{
Log.v("User is login","YES");
}
else
{
Log.v("User is not login","OK");
LoginManager.getInstance().logInWithReadPermissions(WelcomeActivity1.this, (Arrays.asList("public_profile", "user_friends","user_birthday","user_about_me","email")));
}
I'm updating an app that use facebook sdk, but i'm facing some problems, and official documentation is too poor.
On my app, user can log in with facebook or with a normal account (stored on my server), and this options are showed on app startup. Obviously user can also log out and log in with another account (facebook or not), and i have a problem with facebook logout. In fact i'm not able to logout user connected with facebook account.
As i've noticed after a lot of attempts, all changes about facebook status are tracked by AccessTokenTracker and ProfileTracker, that should be instantiated only once at startup.
I show (and explain) my code.
This is code of my login FragmentActivity that check if user was already logged in (with facebook or with dedicated account), and if yes, show next activity, else show fragment for choose access options:
#Override
protected void onCreate(Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if (currentAccessToken != null) {
Log.i("LOGINACTIVITY", "token tracker, current token valid");
AccessToken token = AccessToken.getCurrentAccessToken();
//already logged with facebook, show next activity
} else {
//check if current visible activity is logout activity
// that contains logout button
ActivityManager am = (ActivityManager) LoginActivity.this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
String top_activity = taskInfo.get(0).topActivity.getClassName();
if (top_activity.equals(getApplicationContext().getPackageName() + ".LogoutActivity")) {
//launch new login activity
LoginManager.getInstance().logOut();
getApplicationContext().startActivity(new Intent(getApplicationContext(),
LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
}
};
accessTokenTracker.startTracking();
Now it happen that, when i press logout button, accesstoken tracker execute else branch so show login options it's showed, but for some reason app automatically login again with facebook (it's invoked if branch of TokenTracker), so user is not able to logout from facebook.
What's wrong?
Make sure to stop access token tracker before logging out to avoid getting onCurrentAccessTokenChanged(...) called with a null currentAccessToken, which will cause - According to your code - to execute else clause.
accessTokenTracker.stopTracking();
LoginManager.getInstance().logOut();
And BTW, you don't have to use startTracking() right after executing new AccessTokenTracker(), as AccessTokenTracker() implements startTracking()
AccessTokenTracker.class
public AccessTokenTracker() {
Validate.sdkInitialized();
this.receiver = new AccessTokenTracker.CurrentAccessTokenBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(FacebookSdk.getApplicationContext());
this.startTracking();
}