我正在使用Android Dropbox API。在我的应用程序的主要活动中,我正在对dropbox api进行身份验证调用。问题是,每次我的应用程序启动时,用户都必须点击“允许”以授予应用程序访问其保管箱的权限。我的代码如下:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//clearKeys();
//Log.e(TAG, "keys cleared");
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
mDBApi.getSession().startAuthentication(Main.this);
Log.e(TAG, "started authentication");
protected void onResume() {
super.onResume();
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// MANDATORY call to complete auth.
// Sets the access token on the session
mDBApi.getSession().finishAuthentication();
if(mDBApi.getSession().authenticationSuccessful()){
Log.e(TAG, "Authentication finished");
}
AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair();
// Provide your own storeKeys to persist the access token pair
// A typical way to store tokens is using SharedPreferences
storeKeys(tokens.key, tokens.secret);
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}//end of onResume()
我需要找到一种方法来知道应用程序已经过身份验证,因此如果是这种情况我可以绕过身份验证。我不知道在这一点上该怎么做。有人可以帮忙吗?
答案 0 :(得分:4)
在验证之前,检查存储的访问令牌是否仍然有效(当然,如果您有一个)。为此,只需对通过OAuth公开的任何方法发出授权请求。最好调用一个导致简短输出的方法。 如果此调用因无效/过期令牌而失败,请继续进行身份验证。此时更新存储的令牌,其余的应该像以前一样工作
答案 1 :(得分:2)
你使用过SDK吗?
同步Api SDK:https://www.dropbox.com/developers/sync/tutorial/android
在对Dropbox进行身份验证:
完成后,您应该在LogCat中看到信息级别的消息 说“Dropbox用户链接”。用户只需要这样做 一次,之后SDK会将用户令牌存储在缓存中。什么时候 您的应用重新启动,您可以检查它是否已被链接 调用hasLinkedAccount。
<强>更新
核心API SDK:https://www.dropbox.com/developers/core/setup#android
连接此处的Java文档:https://www.dropbox.com/static/developers/dropbox-android-sdk-1.5.3-docs/index.html
在用户授权后返回您的应用:
finishAuthentication()方法将绑定用户的访问令牌 到会议。您现在可以通过它来检索它们 mDBApi.getSession()。getAccessTokenPair()。
您的应用关闭后,您将再次需要这些令牌,所以就是这样 保存它们以供将来访问很重要。如果你不这样做,用户会 每次他们从您的Dropbox访问他们的Dropbox时都必须重新进行身份验证 应用
实现存储密钥的常用方法是通过Android SharedPreferences API。要了解具体方法,请查看Android 文档。与此同时,为简单起见,上面的代码 假装storeKeys函数调用你想要的任何方法 用于将钥匙存放在更永久的位置。
修改
storeKeys的实现:
public static boolean storeKeys(String key, String secret) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); // this refers to context
SharedPreferences.Editor editor = settings.edit();
editor.putString("key", key);
editor.putString("secret", secret);
return editor.commit();
}