简体   繁体   English

如何在android中保存dropbox api的会话

[英]How to save session of dropbox api in android

I am uploading a file in the dropbox using dropbox api in android.我正在使用 android 中的 dropbox api 在 dropbox 中上传文件。 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:我使用这些代码在 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.为了避免每次都手动授权应用程序连接到用户的 Dropbox 帐户(即调用startAuthentication ),应用程序应存储并重新使用生成的访问令牌,这样只需执行一次。

It seems you already have code to do this in buildSession , using storeKeys and getKeys , which use SharedPreferences to persist the access token.似乎您已经在buildSession中使用了storeKeysgetKeys来执行此操作,它们使用SharedPreferences来保留访问令牌。

So, you just need to know if the AndroidAuthSession already has an access token loaded.因此,您只需要知道AndroidAuthSession已经加载了访问令牌。 You can use the AndroidAuthSession.isLinked method for this:您可以为此使用AndroidAuthSession.isLinked方法:

https://www.dropboxstatic.com/static/developers/dropbox-android-sdk-1.6.3-docs/com/dropbox/client2/session/AbstractSession.html#isLinked() 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.在调用startAuthentication之前调用startAuthentication这样您就可以知道您是否已经拥有访问令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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