i dont know how to use my saved authentication token after restart of my application, so i don´t need to authenticate again.
/*DROPBOX ==========================*/
private String APP_KEY= "key";
private String APP_SECRET= "secret";
AppKeyPair appKeys;
AndroidAuthSession session;
DropboxAPI<AndroidAuthSession> dpAPI;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.readings_main);
//get dropbox keys
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.dp_key_token), Context.MODE_PRIVATE);
// if i use these 2 lines i get exception that my key isn´t set in manifest, and thats true because in manifest i have the first key, not hte generated after auth.
// APP_KEY= sharedPref.getString("key", "key");
// APP_SECRET= sharedPref.getString("secret", "secret");
appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
// setup dropbox session
session = new AndroidAuthSession(appKeys, AccessType.DROPBOX);
dpAPI= new DropboxAPI<AndroidAuthSession>(session);
}
protected void onResume() {
super.onResume();
if (dpAPI.getSession().authenticationSuccessful()) {
try {
// Required to complete auth, sets the access token on the session
dpAPI.getSession().finishAuthentication();
AccessTokenPair tokens = dpAPI.getSession().getAccessTokenPair();
//store keys in sharedpreferences ;
storeKeys(tokens.key, tokens.secret);
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}
public boolean storeKeys(String key, String secret) {
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.dp_key_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", key);
editor.putString("secret", secret);
return editor.commit();
}
Later i use...
dpAPI.getSession().startAuthentication(ADLAppActivity.this);
and then i upload a file, so everything works fine for me. But, after restart App i don´t want to authenticate again. How should i use the saved Token in SharedPref???
Please check this answer.
Instead of calling dpAPI.getSession().startAuthentication(ADLAppActivity.this); you should call session.setOAuth2AccessToken(RESTORED_TOKEN); with your token restored from preferences.
Related
I use twitter4j in my android application. I can get oauth_verifier and fetch token and secret ( with accessToken.getToken() and accessToken.getTokenSecret() ). I store those value.
However,I don't know how to use this value when the app open again.I found something like this.
accessToken = this.twitter.getOAuthAccessToken(requestToken, verifier);
but how can I create requestToken?
when you got the token and the token secret save them in your app , example using SharedPreference
AccessToken accessToken = twitter.getOAuthAccessToken(oathVerifier);
SharedPreferences pref= getSharedPreferences("social_pref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("token",accessToken.getToken());
editor.putString("token_secret",accessToken.getTokenSecret());
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD) {
editor.apply();
}else{
editor.commit();
}
Now you can easily know if there is a stored token and token secret
public boolean doIhaveTokenAndTokenSecret(Context context){
SharedPreferences pref= getSharedPreferences("social_pref",Context.MODE_PRIVATE);
return pref.getString("token",null)!=null && pref.getString("token_secret",null)!=null ;
}
if you have them stored provide them to ConfigurationBuilder object
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
if(doIhaveTokenAndTokenSecret(getApplicationContext()){
SharedPreferences mSharePref = context.getSharedPreferences(Constants.SOCIAL_PREF_NAME, Context.MODE_PRIVATE);
builder.setOAuthAccessToken(mSharePref.getString("token",null));
builder.setOAuthAccessTokenSecret(mSharePref.getString("token_secret",null));
}
Configuration configuration = builder.build();
Twitter mTwitter = new TwitterFactory(configuration).getInstance();
i have multiple places where my app should upload files to Dropbox. when i try to upload a file the app is falling back to browser. if i use the DropboxApi object globally it says DropboxUnlinkedException.
I am posting my code
Dropbox.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We create a new AuthSession so that we can use the Dropbox API.
AndroidAuthSession session = buildSession();
AJ_Constant.mApi = new DropboxAPI<AndroidAuthSession>(session);
// Basic Android widgets
// setContentView(R.layout.main);
if (mLoggedIn) {
logOut();
} else {
// Start the remote authentication
AJ_Constant.mApi.getSession().startAuthentication(DropBox.this);
}
}
#Override
protected void onResume() {
super.onResume();
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:"
+ e.getLocalizedMessage());
Log.i(TAG, "Error authenticating", e);
}
}
}
The code for uploading file is :
(this code is in another file _someX.java)
com.dropbox.client2.DropboxAPI.Entry response = AJ_Constant.mApi.putFile(
AJ_Constant.ReportfileName, inputStream, file.length(),
null, null);
Should i re-build the session or get authentication process done everytime??
Please suggest me any solution
Thanks in advance
From the Android SDK docs (note the last line of code):
A typical authentication flow when no user access token pair is saved
is as follows:
AndroidAuthSession session = new AndroidAuthSession(myAppKeys, myAccessType);
// When user wants to link to Dropbox, within an activity:
session.startOAuth2Authentication(this);
// When user returns to your activity, after authentication:
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
AccessTokenPair tokens = session.getAccessTokenPair();
// Store tokens.key, tokens.secret somewhere
} catch (IllegalStateException e) {
// Error handling
}
}
When a user returns to your app and you have tokens stored, just
create a new session with them:
AndroidAuthSession session = new AndroidAuthSession(
myAppKeys, myAccessType, new AccessTokenPair(storedAccessKey, storedAccessSecret));
I am trying to connect my Android 4+ to Dropbox. I am using the latest version of the Core API provided by Dropbox.
Everything works fine until I try to save the user key and token when the user returns to my app after he authenticated the access using dropboxAPI.getSession().startOAuth2Authentication(activity).
When the user returns to my app after the authentication the following code should save key and token:
public boolean completeLogInAfterAuthentication() {
AndroidAuthSession session = dropboxAPI.getSession();
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
TokenPair tokens = session.getAccessTokenPair();
saveSessionKeys(tokens.key, tokens.secret);
return true;
} catch (IllegalStateExceptione) {
Log.d("MyLog", "Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
Log.d("MyLog", "Error authenticating", e);
}
}
return false;
}
This is quite exactly the code that is used in the DBRoulett Demo provided by Dropbox. Problem is, that session.getAccessTokenPair() returns null.
Because of this I cannot store any key or token and the user has to re-login everytime the app is started. How can I solve this?
All information I found just say, that getAccessTokenPair() could fail with an IllegalStateException but this is not the case here. The case that null is returned is not described anywhere. Any idea what I can do?
getAccessTokenPair is used to get an OAuth 1 access token (and secret). But you used OAuth 2, so you want getOAuth2AccessToken. From the tutorial (https://www.dropbox.com/developers/core/start/android):
protected void onResume() {
super.onResume();
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// Required to complete auth, sets the access token on the session
mDBApi.getSession().finishAuthentication();
String accessToken = mDBApi.getSession().getOAuth2AccessToken();
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}
This is roughly the same thing that's in the DBRoulette sample, though it has code for both OAuth 1 and OAuth 2:
private void storeAuth(AndroidAuthSession session) {
// Store the OAuth 2 access token, if there is one.
String oauth2AccessToken = session.getOAuth2AccessToken();
if (oauth2AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, "oauth2:");
edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
edit.commit();
return;
}
// Store the OAuth 1 access token, if there is one. This is only necessary if
// you're still using OAuth 1.
AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
if (oauth1AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, oauth1AccessToken.key);
edit.putString(ACCESS_SECRET_NAME, oauth1AccessToken.secret);
edit.commit();
return;
}
}
I want to use the dropbox in my application.I developed a sample application for upload and download files and it ask for authentication.
But I don't want to open login popup.
Is it possible access the dropbox by other users using default account(single account) login details?
So any user can use dropbox directly without login popup.
How to set access user access token pair manually.
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
if (mDBApi == null) {
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
// mDBApi.getSession().startAuthentication(Main.this); //kicks off the web-based authentication
//you'll have to use the web-based authentication UI one-time to get the ######### values
String token_key="#########";
String token_seceret="#########";
AccessTokenPair tokens=new AccessTokenPair(token_key,token_seceret);
mDBApi.getSession().setAccessTokenPair(tokens);
// boolean v=mDBApi.getSession().authenticationSuccessful();
}
First time i run application in debug mode with break point i get the token key and token secret of by entering valid log in detail.and saved(noted) that credential and after that i set them manually as above code then can be log in successfully.
Yes. Have a look at their example app DBRoulette.
Please download the project from the below link name as DBRoulette
https://www.dropbox.com/developers/core
And create an app in https://www.dropbox.com/developers and get the api key and secret and add this both in DBRoulette.java and in AndroidManifest.xml ...it works..
In onCreate() write
AppKeyPair pair = new AppKeyPair(ACCESS_KEY, ACCESS_SECRET);
session = new AndroidAuthSession(pair, AccessType.APP_FOLDER);
dropbox = new DropboxAPI<AndroidAuthSession>(session);
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
String key = prefs.getString(ACCESS_KEY, null);
String secret = prefs.getString(ACCESS_SECRET, null);
if (key != null && secret != null) {
Log.d("key secret", key + " " + secret);
AccessTokenPair token = new AccessTokenPair(key, secret);
dropbox.getSession().setAccessTokenPair(token);
}
if (key == null && secret == null)
dropbox.getSession().startAuthentication(DropboxActivity.this);
And in onResume() write
if (dropbox.getSession().isLinked()) {
try {
loggedIn(true);
doAction();
} catch (IllegalStateException e) {
Toast.makeText(this, "Error during Dropbox authentication",
Toast.LENGTH_SHORT).show();
}
} else if (dropbox.getSession().authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
Editor editor = prefs.edit();
editor.putString(ACCESS_KEY, tokens.key);
editor.putString(ACCESS_SECRET, tokens.secret);
editor.commit();
loggedIn(true);
doAction();
} catch (IllegalStateException e) {
Toast.makeText(this, "Error during Dropbox authentication",
Toast.LENGTH_SHORT).show();
}
}
It worked fine for me
My app I'm developing launches the official twitter app new post screen so the user can post a tweet with some extra text added in the intent. I have got this working nicely however things get a little confused if the user is not logged in with the twitter app. The app launches but the user has to sign in, once they've done that the normal twitter screen appears, if they use the back button to get back to my app the new post screen actually appears after hitting back on the twitter feed screen.
Is there any way I can check that a user is actually signed into the twitter app before trying to run the intent?
I think it's a Twitter app internal issue and you can't test for it.
On the other hand you could provide a Dialog warning the user for this matter with a "Do not show this dialog anymore" checkbox so he gets advised and can dimiss forever the Dialog. You could even provide instructions to authenticate insside the Twitter app in this Dialog.
I am using twitter4j lib.
Here I check for the username. If the username is null then there is no user signed in , else I get the username. This user name is available in the access token which I store in shared preference.
username= mySession.getUsername();
username = (username.equals("")) ? "Not logged in" : username;
code for mySession :-
public class MySession {
private SharedPreferences sharedPref;
private Editor editor;
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";
public TwitterSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(AccessToken accessToken, String username) {
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
editor.putString(TWEET_USER_NAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(TWEET_AUTH_KEY, null);
editor.putString(TWEET_AUTH_SECRET_KEY, null);
editor.putString(TWEET_USER_NAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(TWEET_USER_NAME, "");
}
public AccessToken getAccessToken() {
String token = sharedPref.getString(TWEET_AUTH_KEY, null);
String tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
}
Hope this will help you.
Try this function which will in turn returns you true or false.
True : Logged in
False : Not logged in
twitter.getAuthorization() function will throw you an error if it is not logged in by handling this you can find whether user is previously logged in or not.
public static boolean isAuthenticated(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
try {
twitter.getAuthorization();
return true;
} catch (Exception e) {
return false;
}
}
just add these lines in the oncreate() in ur activity
final Session activeSession = Twitter.getInstance().core.getSessionManager().getActiveSession();
if (activeSession != null){
//do someting
}