我试图在
Android应用中使用OAuth.我的工作正常,但有时会在验证阶段遇到问题.在Android中,我启动浏览器以供用户登录和验证.那么回调URL将重定向回我的应用程序.
这是问题.我的应用程序有一个OAuth消费者和提供者作为我的主要类的成员.当浏览器启动认证时,有时我的主要活动被丢弃以节省内存.当回调URL重新启动我的主要Activity时,提供者和消费者是新的实例,因此当我尝试向api发出请求时,它不起作用.如果主要的Activiy在认证阶段没有被释放,那么一切正常,因为我仍然在使用原始的消费者和提供商.
我尝试使用onSaveInstanceState()和onRestoreInstanceState(),但没有成功.当我的回调网址处理时,似乎没有调用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();
- }
- }
我已经测试了这个代码,它的工作原理.