Workshop:Building Social Media Enabled         Android Apps      Mobile 2.0 Open Ideas          Alberto Alonso Ruibal     ...
Who am ITelecommunication Engineer                System Manager                J2EE DeveloperAndroid Developer @ Mobialia...
Other Android learning resourcesI developed the WikiPlaces app as an example forLabAndroid Málaga. This app contain sample...
Why integrate social media?● Get data from social media● App visibility on social networks● Sharing app data (like high sc...
Social media integration demo appAll the examples in this slides arein a sample open-source application:      http://www.m...
The share button    ●   Very easy to implement    ●   We can launch an “ACTION_SEND” intent to be        received by the s...
IntentsAre an Android system that we can use  to launch activities of the same or        different applicationsAn activity...
This shows the activity chooser
Choosing the componentWe can launch an specific activity(the official twitter app in this sample):PackageManager packageMa...
Twitter Integration●   In this sample we will show our timeline●   Twitter uses OAUTH authentication●   Twitter API respon...
Adding signpostLibrary provided in three flavours:●   java.net.HttpUrlConnection●   Apache Commons HTTP (we will use this)...
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 apps consumerkey and secret and insert them in the code:OA...
Authenticating userNow we redirect our users to the authentication URL,specifying a callback URL:public static String CALL...
Twitter AuthenticationTwitter page is opened onthe system web browserThis sample is read-only(no post or follow)
Intercepting Callback URLWe intercept the callback “socialmediademo://twitter” URLmodifying the AndroidManifest.xml:<activ...
Verifying user loginThen, on the receiving activity(TwitterProviderActivity):Uri uri = this.getIntent().getData();String v...
Getting updates from timelineNow we can query Twitter REST API methods: String url ="http://api.twitter.com/1/statuses/hom...
Parsing the JSON responsesAndroid API integrates a JSON parser!JSONArray array = new JSONArray(response);for (int i = 0; i...
Finally we show the updates           On the source code you           can also find:           ●   List adapter for updat...
LinkedIn Integration●   Very similar to Twitter, we can also use    libsignpost●   XML/JSON API●   A small difference: we ...
Getting a LinkedIn API keyhttps://www.linkedin.com/secure/developer
LinkedIn Authentication         Works like Twitter, opening it         on the systems browser.         We also have a call...
Calling the LinkedIn APIBy default in XML, we must send the parameter“&format=json”String response =httpRequest("http://ap...
LinkedIn result     Shows updates from your     LinkedIn contacts
Using social media for logging-inNo need to create a user accountI recommend Facebook:   ● More users   ● More user dataWe...
Facebook Integration●   Uses OAUTH 2.0, signpost does not support it●   Download Facebook SDK from Github:    https://gith...
Getting a Facebook API key (I)https://www.facebook.com/developers/
Getting a Facebook API key (II)Here we have the Application IDTo obtain the key hash: keytool -exportcert -alias androidde...
Preparing the Facebook ObjectAnd launching the facebook authentication...final   int ACTIVITY_CODE = 777;final String appI...
Login with Facebook        Opens a Facebook        Activity requesting        authentication data
Getting user data from FacebookWhen we are authenticated, we can do requests,“/me” gets user informationString res = fb.re...
Improving ads with user data●   With AdMob we can specify user gender and    birthday:AdRequest adRequest = new AdRequest(...
Facebook result    The demo app shows the    user data    The Ad shown is requested    with the user data    We can use th...
More ideas● You can also use a WebView to  integrate social media features● “Follow” button integrating twitter API● “Like...
Questions...Thanks for your attention!       Alberto Alonso Ruibal    alberto.ruibal@mobialia.com      http://www.mobialia...
Upcoming SlideShare
Loading in …5
×

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

2,373 views

Published on

We provide some examples on how to integrate social media on Android apps, from the simple “Share” button to more complex integrations like using Twitter, LinkedIn or Facebook APIs, including logging-in with social media.

As an example we developed a open source “Social Media Demo” application with all the examples in this presentation.

Published in: Technology, Business
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,373
On SlideShare
0
From Embeds
0
Number of Embeds
156
Actions
Shares
0
Downloads
0
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

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

  1. 1. Workshop:Building Social Media Enabled Android Apps Mobile 2.0 Open Ideas Alberto Alonso Ruibal alberto.ruibal@mobialia.com T: @mobialia @albertoruibal
  2. 2. Who am ITelecommunication Engineer System Manager J2EE DeveloperAndroid Developer @ MobialiaChess apps: Mobialia Chess, Internet Chess Club Gas Stations Spain ...My blog: http://www.alonsoruibal.comMy company: http://www.mobialia.com
  3. 3. Other Android learning resourcesI developed the WikiPlaces app as an example forLabAndroid Málaga. This app contain samples of how todo 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. 4. 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
  5. 5. Social media integration demo appAll the examples in this slides arein a sample open-source application: http://www.mobialia.com/mobile20/
  6. 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. 7. IntentsAre an Android system that we can use to launch activities of the same or different applicationsAn activity launches an intent The intent can include “extra” data Other activity receives the intent
  8. 8. This shows the activity chooser
  9. 9. Choosing the componentWe 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);...
  10. 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. 11. Adding signpostLibrary provided in three flavours:● java.net.HttpUrlConnection● Apache Commons HTTP (we will use this)● Jetty HTTP ClientTo use it, download:● signpost-core-1.2.1.1.jar● signpost-commonshttp4-1.2.1.1.jarAnd add them to your build path on Eclipse
  12. 12. Getting a Twitter API key (I)Register your app at https://dev.twitter.com/apps
  13. 13. Getting a Twitter API key (II)Once registered, you can get your apps consumerkey 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. 14. Authenticating userNow 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 tokenaccessToken = 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. 15. Twitter AuthenticationTwitter page is opened onthe system web browserThis sample is read-only(no post or follow)
  16. 16. Intercepting Callback URLWe intercept the callback “socialmediademo://twitter” URLmodifying the AndroidManifest.xml:<activityandroid: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. 17. Verifying user loginThen, 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 tokenaccessToken = oauthConsumer.getToken();tokenSecret = oauthConsumer.getTokenSecret();
  18. 18. Getting updates from timelineNow 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 requestoauthConsumer.setTokenWithSecret(accessToken, tokenSecret);oauthConsumer.sign(request);HttpResponse response = httpClient.execute(request);
  19. 19. Parsing the JSON responsesAndroid 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. 20. Finally we show the updates On the source code you can also find: ● List adapter for updates ● Image Cache
  21. 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. 22. Getting a LinkedIn API keyhttps://www.linkedin.com/secure/developer
  23. 23. LinkedIn Authentication Works like Twitter, opening it on the systems browser. We also have a callback URL
  24. 24. Calling the LinkedIn APIBy 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. 25. LinkedIn result Shows updates from your LinkedIn contacts
  26. 26. Using social media for logging-inNo need to create a user accountI recommend Facebook: ● More users ● More user dataWe can get additional user information! ● Gender ● Birthday ● ...
  27. 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. 28. Getting a Facebook API key (I)https://www.facebook.com/developers/
  29. 29. Getting a Facebook API key (II)Here we have the Application IDTo obtain the key hash: keytool -exportcert -alias androiddebugkey-keystore ~/.android/debug.keystore | openssl sha1 -binary | opensslbase64
  30. 30. Preparing the Facebook ObjectAnd 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. 31. Login with Facebook Opens a Facebook Activity requesting authentication data
  32. 32. Getting user data from FacebookWhen we are authenticated, we can do requests,“/me” gets user informationString 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. 33. 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);
  34. 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. 35. 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
  36. 36. Questions...Thanks for your attention! Alberto Alonso Ruibal alberto.ruibal@mobialia.com http://www.mobialia.com T: @mobialia @albertoruibal

×