Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Salt march 2011-building twitter app

837 views

Published on

Salt march 2011-building twitter app

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Salt march 2011-building twitter app

  1. 1. Building Twitter App Rohit Ghatol
  2. 2. About Me Rohit Ghatol 1. Architect @QuickOffice 2. Project Mgr @Synerzip 3. Certified Scrum Master 4. Author “Beginning PhoneGap” @Apress 5. Founder TechNext Pune (Pune Developer Community) LinkedIn ProfileLinkedIn Profile
  3. 3. Topics – Part 1 • Twitter App Demo • Twitter RestFul API & Java Library • Twitter OAuth • Coding the List Activity • Understanding AsyncTask • Issue with Icons in ListView 3
  4. 4. Topics – Part 2 • Coding different Types of Services • Coding Alarm & Notification Manager • Coding Broadcast Receiver • Coding SQLite DB • Drawbacks of Twitter App • C2DM to Rescue • Understanding C2DM and short Demo 4
  5. 5. Building Twitter App – Part 1 5
  6. 6. Twitter App Demo http://code.google.com/p/DroidTwit t
  7. 7. Youtube Video Demo • http://www.youtube.com/user/rohitssghatol# p/u/13/XhCZpxWDtx0
  8. 8. Twitter Requirements OAuth Authentication OAuth Authentication Fetch Tweets Fetch Tweets Send Tweets Send Tweets Background Sync Background Sync
  9. 9. Overall Architecture
  10. 10. OAuth Authentication
  11. 11. First Time Launch
  12. 12. Asking Service To Fetch Tweets
  13. 13. Triggering Service every n minutes
  14. 14. Phone Boot Event
  15. 15. Battery Low Event
  16. 16. OAuth Short Introduction to OAuth
  17. 17. http://fotofast.comhttp://fotofast.com username password LoginLogin CancelCancel http://fotofast.comhttp://fotofast.com Welcome Rohit Picasa Flickr Print PhotoPrint Photo
  18. 18. http://fotofast.comhttp://fotofast.com username password LoginLogin CancelCancel Welcome Rohit Enter Credentials for Picasa If I go to a restaurant, do I give my ATM Card and Pin to the waiter to pay my bills? Then Why should I give my Picasa Credentials to fotofast.com?
  19. 19. Take 2, Action
  20. 20. http://fotofast.comhttp://fotofast.com username password LoginLogin CancelCancel http://fotofast.comhttp://fotofast.com Welcome Rohit Picasa Flickr Print PhotoPrint Photo
  21. 21. http://picasa.comhttp://picasa.com username password LoginLogin CancelCancel Welcome to Picasa Look Ma its Picasa itself asking for password! http://picasa.comhttp://picasa.com Choose Album to Share with FotoFast Choose Album to Share with FotoFast 11 22 44 55 33 66
  22. 22. http://fotofast.comhttp://fotofast.com Welcome Rohit Picasa Albums Choose photo to Print Photo Choose photo to Print Photo Look Ma! I am able to print picasa photos from FotoFast
  23. 23. Twitter OAuth in Android
  24. 24. About OAuth • The way OAuth works for Web is Browser redirects between the 2 sites • Browser first shows FotoFast, which redirects you to Picasa to authenticate and approve sharing data with FotoFast • On proper Authentication and Approval, Browser takes you back to FotoFast.com
  25. 25. How does the same work for Android Applications?
  26. 26. Steps of Twitter OAuth
  27. 27. Step 1 : Register with Twitter for OAuth Token
  28. 28. Step 2: Register your Activity to handle url “DroidTwit://twitt”
  29. 29. <activity android:name=".OAuthLogin" android:label="@string/app_name” android:launchMode="singleTask"> <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="DroidTwit" android:host="twitt"></data> </intent-filter> </activity>
  30. 30. Step 3: Create a OAuth URL and ask browser to show it OAuth URL also contains CallBack URL you URL can redirect back to your activity
  31. 31. public static final String CALLBACK_URL ="DroidTwitt://twitt"; public void buttonClick(){ OAuthSignpostClient client = new OAuthSignpostClient (TWITTER_KEY, TWITTER_SECRET,CALLBACK_URL); final URI twitterUrl = client.authorizeUrl(); //Start Browser startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(twitterUrl.toString()))); }
  32. 32. Step 4: Handle Response from Browser after OAuth
  33. 33. @Override protected void onNewIntent(final Intent intent) { super.onNewIntent(intent); final Uri uri = intent.getData(); if ((uri != null) && uri.toString().startsWith(CALLBACK_URL)) { verifier = uri.getQueryParameter("oauth_verifier"); client.setAuthorizationCode(verifier); accessTokenAndSecret = client.getAccessToken(); Log.e("NewIntent", "Access token: " + accessTokenAndSecret[0]); Log.e("NewIntent", "Token secret: " + accessTokenAndSecret[1]); }
  34. 34. For more details on OAuth in Android read http://blog.copyninja.info/2010/09/a ndroid-oauth-authentication- with.html
  35. 35. Fetching From Twitter API
  36. 36. Guidelines • Make the fetch module Synchronous List<Tweets> getLatestTweets(); • Either call directly or through Services • Use AsyncTask on UI to avoid ANR
  37. 37. ListView Showing Tweets Lets see a some code for this. http://code.google.com/p/droidtwit/wiki/AndroidListActivityAsyncTaskTutorial
  38. 38. Need for List Adapter Entry 1 1 2 3 4 List<Tweet>List<Tweet> TweetsTweets Something elseSomething else Data that can vary List View functionality is same Layout can vary Adapter LayerAdapter Layer
  39. 39. public class MyAdapter extends BaseAdapter{ public int getCount(){ } public Object getItem(int position){ } public long getItemId(int position){ } public View getView(int position,Convert view,..){ } }
  40. 40. List View Explained Entry 1 Entry 2 Entry 3 Entry 4 1 2 3 4 1 Plank No. PlankPlank
  41. 41. List View Explained Entry 1 Entry 2 Entry 3 Entry 4 1 2 3 4 1 Plank No. Scroll Entry 5 1 Plank 1 Reused when it pops out the top while scrolling
  42. 42. Thumbnails in ListView Common Problem and How to solve it
  43. 43. Why is thumbnail is such a problem in ListView? Entry 1 Entry 2 Entry 3 Entry 4 Thread 1Thread 1 Thread 2Thread 2 Threads to fetch image asynchronously 1 2 3 4 Thread 3Thread 3 Thread 4Thread 4
  44. 44. Why is thumbnail such a problem in ListView? Entry 5 Entry 6 Entry 7 Entry 8 Thread 1Thread 1 Now Thread 1 returns image one and sets it on Plank 1, but Plank 1 should show image from Entry 5. Wrong images are shown for Entry 5, till Thread 5 returns. And for each scroll, again images are fetched 1 2 3 4 Thread 5Thread 5
  45. 45. Solution Entry 1 Entry 2 Entry 3 Entry 4 1 2 3 4 Blocking Queue Thread 1Thread 1 Local Image CacheLocal Image Cache Thread reads from Blocking Queue, checks the Image Cache, if Image not there, fetches it dumps in Image Cache and gives it to the Image View (If position is valid) While Scrolling, we add entries in Blocking Queue
  46. 46. Step 0 1 2 3 4 Blocking Queue Thread 1Thread 1 Local Image CacheLocal Image Cache Continuous Thread started while(true){ PhotoToLoad task = queue.take(); //Fetch photo from internet //Put photo in cache and set on Image View } Thread is blocked on queue.take()
  47. 47. Step 1 …..….. Entry 1 1 2 3 4 PhotoToLoadPhotoToLoad Blocking Queue Thread 1Thread 1 Local Image CacheLocal Image Cache Adapter’s getView() is called Thread now unblocked Continuous Thread started while(true){ PhotoToLoad task = queue.take(); //Fetch photo from internet //Put photo in cache and set on Image View }
  48. 48. Step 1 Entry 1 1 2 3 4 PhotoToLoadPhotoToLoad Blocking Queue Thread 1Thread 1 Local Image CacheLocal Image Cache Adapter’s getView() is called Thread now unblocked Continuous Thread started while(true){ PhotoToLoad task = queue.take(); //Fetch photo from internet //Put photo in cache and set on Image View }
  49. 49. Step 0 3 4 Blocking Queue Thread 1Thread 1 Local Image CacheLocal Image Cache Continuous Thread started while(true){ PhotoToLoad task = queue.take(); //Fetch photo from internet //Put photo in cache and set on Image View } Thread is blocked on queue.take() Entry 1 Entry 2 1 2
  50. 50. Class Diagram <<ImageLoader>><<ImageLoader>> void queue(String url, ImageView imageView); <<ImageCache>><<ImageCache>> void cache(String url, Bitmap bitmap); BitMap get(String url); PhotoToLoadPhotoToLoad private String url; private ImageView imageView; Uses BlockingQueue<PhotoToLoad> and has a thread which keeps running on the BlockingQueue, to either fetch image from cache or from internet
  51. 51. Complete Example • The complete example of the QueuedImageLoader can be found http://code.google.com/p/feedreader/source /browse/trunk/FifaLatestNews/src/com/latest news/cache/QueuedImageLoader.java
  52. 52. Building Twitter App – Part 2 61
  53. 53. Using Services Lets see Code Demos for this Complete Detailed Video of this is available on http://code.google.com/p/droidtwit/wiki/AndroidServiceTutorial
  54. 54. Types of Services • Main Types – Start Service – Bind Service (using Primitives) – Bind Service (using complex types) – Local Service 63
  55. 55. Using Alarm Manager Lets see Code Demo
  56. 56. Listener Battery Event Lets see Code Demo
  57. 57. SQLite Database Demo Lets see Code Demo
  58. 58. Pull Vs Server Push • Twitter App is an example of writing Pull Application • Pull Applications have some drawbacks 67
  59. 59. Drawbacks of DroidTwitt
  60. 60. Battery Drain • Application launching every 5/10/15 mins • Not sure if we will get new information, blindly trying • Way to optimize is using AlarmManager.setInExactRepeating(), but that only helps so much
  61. 61. Data Usage • Polling means more use of Data • If Server is not optimized, then it always sends a chunk of stale data, more bandwidth • Ways to optimize is ask server to send data on top of what the client already has (say use the timestamp), but that only helps so much
  62. 62. Lag • Notification using Polling will always have a Lag • It ends up being a balancing act between Saving Battery and Freshness of the data
  63. 63. Traffic (Server Side) • Every device, Every n minutes bombarding the Server • Businesses won’t mind traffic as long it is adding real value. But is this real value?
  64. 64. Load (Server Side) • Hitting Database blindly when getting traffic • Servers need to optimized to know whether the polling requests will repeat very n minutes and they only hit database if they have change.
  65. 65. C2DM Players
  66. 66. Google CloudGoogle Cloud Application Server Application Server But Remember a User can have more than one Device!
  67. 67. Android C2DM to Rescue
  68. 68. Google CloudGoogle Cloud Application Server Application Server Step 1: App Server goes Authentication with Google C2DM Cloud and gets a security token Security Token AppServer123
  69. 69. Google CloudGoogle Cloud Application Server Application Server Step 2: Device 1 Registers itself to Google C2DM Cloud, gets an Registration Id Security Token AppServer123
  70. 70. Google CloudGoogle Cloud Application Server Application Server Step 3: Device 1 tells App Server that its C2DM Reg Id is XYZ Device Info Reg Id Rohit’s Phone XYZ XYZ Security Token AppServer123
  71. 71. Google CloudGoogle Cloud Application Server Application Server Device Info Reg Id Rohit’s Phone XYZ Step 4: App Server sends message to C2DM intended for Device with Reg Id XYZ Security Token AppServer123
  72. 72. Google CloudGoogle Cloud Application Server Application Server Device Info Reg Id Rohit’s Phone XYZ Step 6: Google C2DM Cloud Service sends Intent to Device with Reg id XYZ Security Token AppServer123
  73. 73. Google CloudGoogle Cloud Application Server Application Server Device Info Reg Id Rohit’s Phone XYZ Step 7: Device fetches data from App Server to process Security Token AppServer123
  74. 74. C2DM Demo Lets see the Demo
  75. 75. Q & A 91
  76. 76. More about Me • Twitter - http://twitter.com/#!/rohitghatol • TechGig - http://www.techgig.com/rohitghatol • LinkedIn - http://www.linkedin.com/in/rohitghatol • Presentations - www.slideshare.net/rohitsghatol/ • YouTube Tutorials - http://www.youtube.com/user/rohitssghatol

×