Communicating between an activity and the browser - callback


SDK Version: 
M3

A few days ago Gabor made an article about communicating between activites. I'm currently working on a pet project that uses Oauth with the google data api, where I had to get a response from the browser, so let's take a look at communicating between an activity and a browser.

All the tutorials that I found on the net use onResume to get the response, but I can't recommend that, because onResume runs even on the first run of the app (see lifecycle) which is unnecessary in this case.

To sum up the logic:

  • open the browser with a callback url provided
  • user enters credentials
  • the callback will take the result info back to the app that called the browser.

Opening the browser:
We need to use a service that uses browser callback, for example Google data api (Oauth) via Signpost.

  1. ...
  2. String url = provider.retrieveRequestToken(consumer, "putyourappnamehere:///");
  3. startActivity(new Intent(Intent.ACTION_VIEW, url));  
  4. ...

  1. protected void onNewIntent(Intent intent) {
  2.   super.onNewIntent(intent);
  3.   setIntent(intent);//must store the new intent so getIntent() won't return the old one
  4.   processResponse()
  5. }
  6.  
  7. private void processResponse(){
  8.   Intent intent = getIntent();
  9.   Uri uri = this.getIntent().getData();  //get your data here
  10. }

You also need an intent filter in the manifest, that will "catch" the response.

  1. ...
  2. <intent-filter>  
  3. <action android:name="android.intent.action.VIEW"></action>  
  4. <category android:name="android.intent.category.DEFAULT"></category>  
  5. <category android:name="android.intent.category.BROWSABLE"></category>  
  6. <data android:scheme="putyourappnamehere"></data>
  7. </intent-filter>
  8. ...

Please note that in the code it should look like this: "putyourappnamehere:///", and in the manifest it's just "putyourappnamehere".