我正在尝试在Android应用中使用OAuth.我有它正常工作但有时在身份验证阶段遇到问题.在Android中,我启动浏览器以供用户登录和验证.然后回调网址将重定向回我的应用程序.
这是问题所在.我的应用程序有一个OAuth使用者和提供者作为我的主类的成员.当浏览器启动进行身份验证时,有时会丢弃我的主Activity以节省内存.当回调url重新启动我的主Activity时,提供者和使用者是新实例,因此当我尝试向api发出请求时,它不起作用.如果在身份验证阶段没有释放主要的Activiy,那么一切正常,因为我仍然在与原始的消费者和提供者合作.
我尝试使用onSaveInstanceState()和onRestoreInstanceState(),但没有成功.当我的回调url被处理时,似乎没有调用onRestoreInstanceState().似乎直接进入onResume().
在这种情况下,持久化消费者和提供者的正确方法是什么?
完整的保存/恢复解决方案
除了request_token和之外token_secret,isOauth10a()在提供者中恢复状态也很重要。未来可能会有更多状态信息。因此,我最喜欢持久加载解决方案。
我扩展了GrkEngineer的解决方案,使其更加完整。它保存/恢复提供者和消费者,处理所有异常,并在恢复时设置 httpClient。
protected void loadProviderConsumer()
{
try {
FileInputStream fin = this.openFileInput("tmp_provider.dat");
ObjectInputStream ois = new ObjectInputStream(fin);
provider = (CommonsHttpOAuthProvider) ois.readObject();
provider.setHttpClient(httpClient);
ois.close();
fin.close();
fin = this.openFileInput("tmp_consumer.dat");
ois = new ObjectInputStream(fin);
consumer = (CommonsHttpOAuthConsumer) ois.readObject();
ois.close();
fin.close();
Log.d("OAuthTwitter", "Loaded state");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
protected void persistProviderConsumer()
{
try {
FileOutputStream fout = this.openFileOutput("tmp_provider.dat", MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(provider);
oos.close();
fout.close();
fout = this.openFileOutput("tmp_consumer.dat", MODE_PRIVATE);
oos = new ObjectOutputStream(fout);
oos.writeObject(consumer);
oos.close();
fout.close();
Log.d("OAuthTwitter", "Saved state");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经测试了这段代码并且它有效。
| 归档时间: |
|
| 查看次数: |
4495 次 |
| 最近记录: |