Android中的OAuth实例状态

前端之家收集整理的这篇文章主要介绍了Android中的OAuth实例状态前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在 Android应用中使用OAuth.我的工作正常,但有时会在验证阶段遇到问题.在Android中,我启动浏览器以供用户登录和验证.那么回调URL将重定向回我的应用程序.

这是问题.我的应用程序有一个OAuth消费者和提供者作为我的主要类的成员.当浏览器启动认证时,有时我的主要活动被丢弃以节省内存.当回调URL重新启动我的主要Activity时,提供者和消费者是新的实例,因此当我尝试向api发出请求时,它不起作用.如果主要的Activiy在认证阶段没有被释放,那么一切正常,因为我仍然在使用原始的消费者和提供商.

我尝试使用onSaveInstanceState()和onRestoreInstanceState(),但没有成功.当我的回调网址处理时,似乎没有调用onRestoreInstanceState().似乎直接去onResume().

在这种情况下,坚持消费者和提供者的正确方法是什么?

解决方法

完成保存/恢复解决方

除了request_token和token_secret之外,isOauth10a()状态对于在提供程序中还原很重要.未来可能会有更多的国家信息.因此,我喜欢持久化和负载解决方案.

我扩展了GrkEngineer的解决方案,使其更加完整.它保存/恢复提供者和消费者,处理所有异常,并在还原时设置httpClient.

  1. protected void loadProviderConsumer()
  2. {
  3. try {
  4. FileInputStream fin = this.openFileInput("tmp_provider.dat");
  5. ObjectInputStream ois = new ObjectInputStream(fin);
  6. provider = (CommonsHttpOAuthProvider) ois.readObject();
  7. provider.setHttpClient(httpClient);
  8. ois.close();
  9. fin.close();
  10.  
  11. fin = this.openFileInput("tmp_consumer.dat");
  12. ois = new ObjectInputStream(fin);
  13. consumer = (CommonsHttpOAuthConsumer) ois.readObject();
  14. ois.close();
  15. fin.close();
  16.  
  17. Log.d("OAuthTwitter","Loaded state");
  18. } catch (FileNotFoundException e) {
  19. e.printStackTrace();
  20. } catch (StreamCorruptedException e) {
  21. e.printStackTrace();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. } catch (ClassNotFoundException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28.  
  29. protected void persistProviderConsumer()
  30. {
  31.  
  32. try {
  33. FileOutputStream fout = this.openFileOutput("tmp_provider.dat",MODE_PRIVATE);
  34. ObjectOutputStream oos = new ObjectOutputStream(fout);
  35. oos.writeObject(provider);
  36. oos.close();
  37. fout.close();
  38.  
  39. fout = this.openFileOutput("tmp_consumer.dat",MODE_PRIVATE);
  40. oos = new ObjectOutputStream(fout);
  41. oos.writeObject(consumer);
  42. oos.close();
  43. fout.close();
  44.  
  45. Log.d("OAuthTwitter","Saved state");
  46. } catch (FileNotFoundException e) {
  47. e.printStackTrace();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. }

我已经测试了这个代码,它的工作原理.

猜你在找的Android相关文章