简体   繁体   中英

How to save session of dropbox api in android

I am uploading a file in the dropbox using dropbox api in android. I have successfully uploaded file in the dropbox but problem is that each time i need to allow the access of dropbox. Each time i have to go to the browser and allow the access. I dont know how to solve this issue. I have used these codes to upload files in dropbox:

public class DropboxFileUploadMainForContact extends Activity {
private static final int TAKE_PHOTO = 1;
 final String DIR = "/";
private File f;
private boolean mLoggedIn, onResume;
public DropboxAPI<AndroidAuthSession> mApi;
String upload_filepath = "abc/";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // get the file which we want to upload
    Bundle b = getIntent().getExtras();
    upload_filepath = upload_filepath + b.getString("fileNameToUpload");

    AndroidAuthSession session = buildSession();
    mApi = new DropboxAPI<AndroidAuthSession>(session);

    setLoggedIn(false);

    createDir();
    if (mLoggedIn) {
        logOut();
    }
    if (Utils.isOnline(DropboxFileUploadMainForContact.this)) {
        mApi.getSession().startAuthentication(DropboxFileUploadMainForContact.this);
        onResume = true;
    } else {
        Utils.showNetworkAlert(DropboxFileUploadMainForContact.this);
        finish();
    }




}

private AndroidAuthSession buildSession() {
    AppKeyPair appKeyPair = new AppKeyPair(Constants.DROPBOX_APP_KEY,
            Constants.DROPBOX_APP_SECRET);
    AndroidAuthSession session;

    String[] stored = getKeys();
    if (stored != null) {
        AccessTokenPair accessToken = new AccessTokenPair(stored[0],
                stored[1]);
        session = new AndroidAuthSession(appKeyPair, Constants.ACCESS_TYPE,
                accessToken);
    } else {
        session = new AndroidAuthSession(appKeyPair, Constants.ACCESS_TYPE);
    }

    return session;
}

private String[] getKeys() {
    SharedPreferences prefs = getSharedPreferences(
            Constants.ACCOUNT_PREFS_NAME, 0);
    String key = prefs.getString(Constants.ACCESS_KEY_NAME, null);
    String secret = prefs.getString(Constants.ACCESS_SECRET_NAME, null);
    if (key != null && secret != null) {
        String[] ret = new String[2];
        ret[0] = key;
        ret[1] = secret;
        return ret;
    } else {
        return null;
    }
}

private void logOut() {
    mApi.getSession().unlink();

    clearKeys();
}

private void clearKeys() {
    SharedPreferences prefs = getSharedPreferences(
            Constants.ACCOUNT_PREFS_NAME, 0);
    Editor edit = prefs.edit();
    edit.clear();
    edit.commit();
}

private void createDir() {
    File dir = new File(Utils.getPath());
    if (!dir.exists()) {
        dir.mkdirs();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == TAKE_PHOTO) {
            // f = new File(Utils.getPath() + "/temp.jpg");
            if (Utils.isOnline(DropboxFileUploadMainForContact.this)) {
                mApi.getSession().startAuthentication(
                        DropboxFileUploadMainForContact.this);
                onResume = true;
            } else {
                Utils.showNetworkAlert(DropboxFileUploadMainForContact.this);
            }
        }
    }
}

public void setLoggedIn(boolean loggedIn) {
    mLoggedIn = loggedIn;
    if (loggedIn) {
        // new
        // Now make a backup file of sms
        // BackUpAllSms();

        DropboxFileUpload uploadFile = new DropboxFileUpload(this, mApi,
                DIR, upload_filepath);
        uploadFile.execute();

        onResume = false;
        finish();

    }
}





private void storeKeys(String key, String secret) {
    SharedPreferences prefs = getSharedPreferences(
            Constants.ACCOUNT_PREFS_NAME, 0);
    Editor edit = prefs.edit();
    edit.putString(Constants.ACCESS_KEY_NAME, key);
    edit.putString(Constants.ACCESS_SECRET_NAME, secret);
    edit.commit();
}

private void showToast(String msg) {
    Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
    error.show();
}

@Override
protected void onResume() {

    try {
        AndroidAuthSession session = mApi.getSession();

        Log.d("ppp", "session.authenticationSuccessful() on resume = "+session.authenticationSuccessful());
        if (session.authenticationSuccessful()) {
            try {
                session.finishAuthentication();

                TokenPair tokens = session.getAccessTokenPair();
                storeKeys(tokens.key, tokens.secret);
                setLoggedIn(onResume);
            } catch (IllegalStateException e) {
                showToast("Couldn't authenticate with Dropbox:"
                        + e.getLocalizedMessage());
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    super.onResume();
}

}

Could anyone tell me how to solve this issue??

In order to avoid having to authorize the app to connect to the user's Dropbox account manually each time (ie, calling startAuthentication ), the app should store and re-use the resulting access token, so that this only needs to be done once.

It seems you already have code to do this in buildSession , using storeKeys and getKeys , which use SharedPreferences to persist the access token.

So, you just need to know if the AndroidAuthSession already has an access token loaded. You can use the AndroidAuthSession.isLinked method for this:

https://www.dropboxstatic.com/static/developers/dropbox-android-sdk-1.6.3-docs/com/dropbox/client2/session/AbstractSession.html#isLinked()

Call that before calling startAuthentication so you can know if you already have an access token.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM