Workshop:

Building Social Media Enabled
         Android Apps
      Mobile 2.0 Open Ideas
          Alberto Alonso Ruibal
       alberto.ruibal@mobialia.com
       T: @mobialia @albertoruibal
Who am I
Telecommunication Engineer
                System Manager
                J2EE Developer
Android Developer @ Mobialia
Chess apps: Mobialia Chess, Internet Chess Club
               Gas Stations Spain
                       ...
My blog: http://www.alonsoruibal.com
My company: http://www.mobialia.com
Other Android learning resources
I developed the WikiPlaces app as an example for
LabAndroid Málaga. This app contain samples of how to
do many common things on Android:
●   Dashboard
●   Creating preferences screens and retrieving preferences
●   Google Maps API, including overlays, Location API
●   Using external JSON sevices
●   Lists and adapters
●   Launching external apps with Intents
●   AdMob integration
           http://www.mobialia.com/labandroid
Why integrate social media?

● Get data from social media
● App visibility on social networks


● Sharing app data (like high scores)


● Easy login for your users on your app


● Get additional user data
Social media integration demo app




All the examples in this slides are
in a sample open-source application:

      http://www.mobialia.com/mobile20/
The share button
    ●   Very easy to implement
    ●   We can launch an “ACTION_SEND” intent to be
        received by the social media applications

    public void onShareChoose(View v) {
   String shareText = ((EditText) findViewById(R.id.EditText)
).getText().toString();
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(android.content.Intent.EXTRA_TEXT, shareText);
   startActivity(Intent.createChooser(intent,
getResources().getText(R.string.share_choose)));
}
Intents
Are an Android system that we can use
  to launch activities of the same or
        different applications

An activity launches an intent
  The intent can include “extra” data
        Other activity receives the intent
This shows the activity chooser
Choosing the component
We can launch an specific activity
(the official twitter app in this sample):

PackageManager packageManager = context.getPackageManager();

List<ResolveInfo> activityList = packageManager.queryIntentActivities(intent, 0);

for (ResolveInfo act : activityList) {

 if (act.activityInfo.name.indexOf("com.twitter.") == 0) { // Check it if starts by...

  ComponentName name = new ComponentName(act.activityInfo.applicationInfo.packageName,
act.activityInfo.name);

  intent.setComponent(name);

  startActivity(intent);

...
Twitter Integration

●   In this sample we will show our timeline
●   Twitter uses OAUTH authentication
●   Twitter API response is JSON
●   Multiple options, I prefer libsignpost
    http://code.google.com/p/oauth-signpost/
Adding signpost
Library provided in three flavours:
●   java.net.HttpUrlConnection
●   Apache Commons HTTP (we will use this)
●   Jetty HTTP Client
To use it, download:
●   signpost-core-1.2.1.1.jar
●   signpost-commonshttp4-1.2.1.1.jar
And add them to your build path on Eclipse
Getting a Twitter API key (I)
Register your app at https://dev.twitter.com/apps
Getting a Twitter API key (II)
Once registered, you can get your app's consumer
key and secret and insert them in the code:




OAuthConsumer oauthConsumer = new CommonsHttpOAuthConsumer(
  // the consumer key of this app (replace this with yours)
  "RFbRzd0BzYGZjrDd02ec5g" ,
  // the consumer secret of this app (replace this with yours)
  "wo9lKhzwpEfdXS2Z3dO2W092W9pMoJGrc5kUsBdA");
Authenticating user
Now we redirect our users to the authentication URL,
specifying a callback URL:
public static String CALLBACK_URL = "socialmediademo://twitter";
//...
 String authUrl = oauthProvider.retrieveRequestToken(oauthConsumer,
CALLBACK_URL);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl));
// save token
accessToken     = oauthConsumer.getToken();
tokenSecret = oauthConsumer.getTokenSecret();
 intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND |
Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Twitter Authentication



Twitter page is opened on
the system web browser


This sample is read-only
(no post or follow)
Intercepting Callback URL
We intercept the callback “socialmediademo://twitter” URL
modifying the AndroidManifest.xml:
<activity
android:name =".TwitterProviderActivity"
android:label ="@string/app_name">
<intent-filter>
 <action android:name="android.intent.action.VIEW"></action>
 <category android:name="android.intent.category.DEFAULT"></category>
 <category android:name="android.intent.category.BROWSABLE"></category>
 <data android:scheme="socialmediademo" android:host="twitter"></data>
</intent-filter>
</activity>
Verifying user login
Then, on the receiving activity
(TwitterProviderActivity):

Uri uri = this.getIntent().getData();
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
oauthConsumer.setTokenWithSecret(accessToken, tokenSecret);
oauthProvider.retrieveAccessToken(oauthConsumer, verifier);
// save new token
accessToken   = oauthConsumer.getToken();
tokenSecret = oauthConsumer.getTokenSecret();
Getting updates from timeline
Now we can query Twitter REST API methods:

 String url =
"http://api.twitter.com/1/statuses/home_timeline.json?count=100";
HttpGet request = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
// sign the request
oauthConsumer.setTokenWithSecret(accessToken, tokenSecret);
oauthConsumer.sign(request);
HttpResponse response = httpClient.execute(request);
Parsing the JSON responses
Android API integrates a JSON parser!

JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
    JSONObject user = object.getJSONObject("user");
    Update update = new Update();
  update.setMessage(Html.fromHtml(object.getString("text")
).toString());
    update.setUserId(user.getString("screen_name"));
    update.setUserName(user.getString("name"));
// ...
Finally we show the updates

           On the source code you
           can also find:
           ●   List adapter for updates
           ●   Image Cache
LinkedIn Integration
●   Very similar to Twitter, we can also use
    libsignpost
●   XML/JSON API
●   A small difference: we need to specify to
    signpost that LinkedIn uses OAUTH version
    1.0a:
     oauthProvider.setOAuth10a(true);
Getting a LinkedIn API key
https://www.linkedin.com/secure/developer
LinkedIn Authentication


         Works like Twitter, opening it
         on the system's browser.


         We also have a callback URL
Calling the LinkedIn API
By default in XML, we must send the parameter
“&format=json”

String response =
httpRequest("http://api.linkedin.com/v1/people/~/network/updates?
count=100&format=json");
if (response != null) {
JSONObject object = new JSONObject(response);
//...
LinkedIn result


     Shows updates from your
     LinkedIn contacts
Using social media for logging-in
No need to create a user account
I recommend Facebook:
   ● More users


   ● More user data


We can get additional user information!
   ● Gender


   ● Birthday


   ● ...
Facebook Integration

●   Uses OAUTH 2.0, signpost does not support it
●   Download Facebook SDK from Github:
    https://github.com/facebook/facebook-android-sdk/
●   We need to add the Facebook SDK as a
    separate project and add a project dependency
●   Use the new Graph API methods!
Getting a Facebook API key (I)
https://www.facebook.com/developers/
Getting a Facebook API key (II)
Here we have the Application ID
To obtain the key hash: keytool -exportcert -alias androiddebugkey
-keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl
base64
Preparing the Facebook Object
And launching the facebook authentication...

final   int ACTIVITY_CODE = 777;
final String appId = "219172308103195";
final String[] PERMISSIONS = new String[] { "user_birthday" };


Facebook fb = new Facebook(appId);
fb.authorize(this, PERMISSIONS, ACTIVITY_CODE, this);
// (Callback not detailed)
Login with Facebook

        Opens a Facebook
        Activity requesting
        authentication data
Getting user data from Facebook
When we are authenticated, we can do requests,
“/me” gets user information

String res = fb.request("/me");
JSONObject object = new JSONObject(res);
Log.d(TAG, object.getString("id"));
Log.d(TAG, object.getString("name"));
Log.d(TAG, object.getString("gender"));
Log.d(TAG, object.getString("birthday"));
Improving ads with user data
●   With AdMob we can specify user gender and
    birthday:
AdRequest adRequest = new AdRequest();
adRequest.setGender(Gender.FEMALE);
adRequest.setBirthday("19790129");
AdView adView = (AdView) this.findViewById(R.id.adView)
adView.loadAd(adRequest);
Facebook result
    The demo app shows the
    user data
    The Ad shown is requested
    with the user data
    We can use the user data on
    may parts of our application
More ideas
● You can also use a WebView to
  integrate social media features
● “Follow” button integrating twitter API


● “Like” button: needs to create a

  facebook object associated
● “Foursquare” API integration
Questions...


Thanks for your attention!


       Alberto Alonso Ruibal
    alberto.ruibal@mobialia.com
      http://www.mobialia.com
    T: @mobialia @albertoruibal

Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android

  • 1.
    Workshop: Building Social MediaEnabled Android Apps Mobile 2.0 Open Ideas Alberto Alonso Ruibal alberto.ruibal@mobialia.com T: @mobialia @albertoruibal
  • 2.
    Who am I TelecommunicationEngineer System Manager J2EE Developer Android Developer @ Mobialia Chess apps: Mobialia Chess, Internet Chess Club Gas Stations Spain ... My blog: http://www.alonsoruibal.com My company: http://www.mobialia.com
  • 3.
    Other Android learningresources I developed the WikiPlaces app as an example for LabAndroid Málaga. This app contain samples of how to do many common things on Android: ● Dashboard ● Creating preferences screens and retrieving preferences ● Google Maps API, including overlays, Location API ● Using external JSON sevices ● Lists and adapters ● Launching external apps with Intents ● AdMob integration http://www.mobialia.com/labandroid
  • 4.
    Why integrate socialmedia? ● Get data from social media ● App visibility on social networks ● Sharing app data (like high scores) ● Easy login for your users on your app ● Get additional user data
  • 5.
    Social media integrationdemo app All the examples in this slides are in a sample open-source application: http://www.mobialia.com/mobile20/
  • 6.
    The share button ● Very easy to implement ● We can launch an “ACTION_SEND” intent to be received by the social media applications public void onShareChoose(View v) { String shareText = ((EditText) findViewById(R.id.EditText) ).getText().toString(); Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(android.content.Intent.EXTRA_TEXT, shareText); startActivity(Intent.createChooser(intent, getResources().getText(R.string.share_choose))); }
  • 7.
    Intents Are an Androidsystem that we can use to launch activities of the same or different applications An activity launches an intent The intent can include “extra” data Other activity receives the intent
  • 8.
    This shows theactivity chooser
  • 9.
    Choosing the component Wecan launch an specific activity (the official twitter app in this sample): PackageManager packageManager = context.getPackageManager(); List<ResolveInfo> activityList = packageManager.queryIntentActivities(intent, 0); for (ResolveInfo act : activityList) { if (act.activityInfo.name.indexOf("com.twitter.") == 0) { // Check it if starts by... ComponentName name = new ComponentName(act.activityInfo.applicationInfo.packageName, act.activityInfo.name); intent.setComponent(name); startActivity(intent); ...
  • 10.
    Twitter Integration ● In this sample we will show our timeline ● Twitter uses OAUTH authentication ● Twitter API response is JSON ● Multiple options, I prefer libsignpost http://code.google.com/p/oauth-signpost/
  • 11.
    Adding signpost Library providedin three flavours: ● java.net.HttpUrlConnection ● Apache Commons HTTP (we will use this) ● Jetty HTTP Client To use it, download: ● signpost-core-1.2.1.1.jar ● signpost-commonshttp4-1.2.1.1.jar And add them to your build path on Eclipse
  • 12.
    Getting a TwitterAPI key (I) Register your app at https://dev.twitter.com/apps
  • 13.
    Getting a TwitterAPI key (II) Once registered, you can get your app's consumer key and secret and insert them in the code: OAuthConsumer oauthConsumer = new CommonsHttpOAuthConsumer( // the consumer key of this app (replace this with yours) "RFbRzd0BzYGZjrDd02ec5g" , // the consumer secret of this app (replace this with yours) "wo9lKhzwpEfdXS2Z3dO2W092W9pMoJGrc5kUsBdA");
  • 14.
    Authenticating user Now weredirect our users to the authentication URL, specifying a callback URL: public static String CALLBACK_URL = "socialmediademo://twitter"; //... String authUrl = oauthProvider.retrieveRequestToken(oauthConsumer, CALLBACK_URL); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)); // save token accessToken = oauthConsumer.getToken(); tokenSecret = oauthConsumer.getTokenSecret(); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent);
  • 15.
    Twitter Authentication Twitter pageis opened on the system web browser This sample is read-only (no post or follow)
  • 16.
    Intercepting Callback URL Weintercept the callback “socialmediademo://twitter” URL modifying the AndroidManifest.xml: <activity android:name =".TwitterProviderActivity" android:label ="@string/app_name"> <intent-filter> <action android:name="android.intent.action.VIEW"></action> <category android:name="android.intent.category.DEFAULT"></category> <category android:name="android.intent.category.BROWSABLE"></category> <data android:scheme="socialmediademo" android:host="twitter"></data> </intent-filter> </activity>
  • 17.
    Verifying user login Then,on the receiving activity (TwitterProviderActivity): Uri uri = this.getIntent().getData(); String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER); oauthConsumer.setTokenWithSecret(accessToken, tokenSecret); oauthProvider.retrieveAccessToken(oauthConsumer, verifier); // save new token accessToken = oauthConsumer.getToken(); tokenSecret = oauthConsumer.getTokenSecret();
  • 18.
    Getting updates fromtimeline Now we can query Twitter REST API methods: String url = "http://api.twitter.com/1/statuses/home_timeline.json?count=100"; HttpGet request = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); // sign the request oauthConsumer.setTokenWithSecret(accessToken, tokenSecret); oauthConsumer.sign(request); HttpResponse response = httpClient.execute(request);
  • 19.
    Parsing the JSONresponses Android API integrates a JSON parser! JSONArray array = new JSONArray(response); for (int i = 0; i < array.length(); i++) { JSONObject user = object.getJSONObject("user"); Update update = new Update(); update.setMessage(Html.fromHtml(object.getString("text") ).toString()); update.setUserId(user.getString("screen_name")); update.setUserName(user.getString("name")); // ...
  • 20.
    Finally we showthe updates On the source code you can also find: ● List adapter for updates ● Image Cache
  • 21.
    LinkedIn Integration ● Very similar to Twitter, we can also use libsignpost ● XML/JSON API ● A small difference: we need to specify to signpost that LinkedIn uses OAUTH version 1.0a: oauthProvider.setOAuth10a(true);
  • 22.
    Getting a LinkedInAPI key https://www.linkedin.com/secure/developer
  • 23.
    LinkedIn Authentication Works like Twitter, opening it on the system's browser. We also have a callback URL
  • 24.
    Calling the LinkedInAPI By default in XML, we must send the parameter “&format=json” String response = httpRequest("http://api.linkedin.com/v1/people/~/network/updates? count=100&format=json"); if (response != null) { JSONObject object = new JSONObject(response); //...
  • 25.
    LinkedIn result Shows updates from your LinkedIn contacts
  • 26.
    Using social mediafor logging-in No need to create a user account I recommend Facebook: ● More users ● More user data We can get additional user information! ● Gender ● Birthday ● ...
  • 27.
    Facebook Integration ● Uses OAUTH 2.0, signpost does not support it ● Download Facebook SDK from Github: https://github.com/facebook/facebook-android-sdk/ ● We need to add the Facebook SDK as a separate project and add a project dependency ● Use the new Graph API methods!
  • 28.
    Getting a FacebookAPI key (I) https://www.facebook.com/developers/
  • 29.
    Getting a FacebookAPI key (II) Here we have the Application ID To obtain the key hash: keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
  • 30.
    Preparing the FacebookObject And launching the facebook authentication... final int ACTIVITY_CODE = 777; final String appId = "219172308103195"; final String[] PERMISSIONS = new String[] { "user_birthday" }; Facebook fb = new Facebook(appId); fb.authorize(this, PERMISSIONS, ACTIVITY_CODE, this); // (Callback not detailed)
  • 31.
    Login with Facebook Opens a Facebook Activity requesting authentication data
  • 32.
    Getting user datafrom Facebook When we are authenticated, we can do requests, “/me” gets user information String res = fb.request("/me"); JSONObject object = new JSONObject(res); Log.d(TAG, object.getString("id")); Log.d(TAG, object.getString("name")); Log.d(TAG, object.getString("gender")); Log.d(TAG, object.getString("birthday"));
  • 33.
    Improving ads withuser data ● With AdMob we can specify user gender and birthday: AdRequest adRequest = new AdRequest(); adRequest.setGender(Gender.FEMALE); adRequest.setBirthday("19790129"); AdView adView = (AdView) this.findViewById(R.id.adView) adView.loadAd(adRequest);
  • 34.
    Facebook result The demo app shows the user data The Ad shown is requested with the user data We can use the user data on may parts of our application
  • 35.
    More ideas ● Youcan also use a WebView to integrate social media features ● “Follow” button integrating twitter API ● “Like” button: needs to create a facebook object associated ● “Foursquare” API integration
  • 36.
    Questions... Thanks for yourattention! Alberto Alonso Ruibal alberto.ruibal@mobialia.com http://www.mobialia.com T: @mobialia @albertoruibal