Salt march 2011-building twitter app
-
Upload
rohit-ghatol -
Category
Technology
-
view
102 -
download
0
description
Transcript of Salt march 2011-building twitter app
Building Twitter App
Rohit Ghatol
About MeRohit Ghatol
1. Architect @QuickOffice2. Project Mgr @Synerzip3. Certified Scrum Master4. Author “Beginning PhoneGap” @Apress5. Founder TechNext Pune (Pune Developer
Community)
LinkedIn ProfileLinkedIn Profile
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
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
Building Twitter App – Part 1
5
Twitter App Demo
http://code.google.com/p/DroidTwitt
Youtube Video Demo
• http://www.youtube.com/user/rohitssghatol#p/u/13/XhCZpxWDtx0
Twitter Requirements
OAuth Authentication
OAuth AuthenticationFetch TweetsFetch Tweets
Send TweetsSend Tweets
Background SyncBackground Sync
Overall Architecture
OAuth Authentication
First Time Launch
Asking Service To Fetch Tweets
Triggering Service every n minutes
Phone Boot Event
Battery Low Event
OAuth
Short Introduction to OAuth
http://fotofast.comhttp://fotofast.com
username
password
LoginLogin CancelCancel
http://fotofast.comhttp://fotofast.comWelcome Rohit
Picasa Flickr
Print PhotoPrint Photo
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?
Take 2, Action
http://fotofast.comhttp://fotofast.com
username
password
LoginLogin CancelCancel
http://fotofast.comhttp://fotofast.comWelcome Rohit
Picasa Flickr
Print PhotoPrint Photo
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
http://fotofast.comhttp://fotofast.comWelcome Rohit
Picasa Albums
Choose photo to Print Photo
Choose photo to Print Photo
Look Ma! I am able to print picasa photos from FotoFast
Twitter OAuth in Android
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
How does the same work for Android Applications?
Steps of Twitter OAuth
Step 1 : Register with Twitter for OAuth Token
Step 2: Register your Activity to handle url “DroidTwit://twitt”
<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>
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
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 BrowserstartActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(twitterUrl.toString())));}
Step 4: Handle Response from Browser after OAuth
@Overrideprotected 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]);}
}
For more details on OAuth in Android read
http://blog.copyninja.info/2010/09/android-oauth-authentication-with.html
Fetching From Twitter API
Guidelines
• Make the fetch module SynchronousList<Tweets> getLatestTweets();
• Either call directly or through Services
• Use AsyncTask on UI to avoid ANR
ListView Showing Tweets
Lets see a some code for this.
http://code.google.com/p/droidtwit/wiki/AndroidListActivityAsyncTaskTutorial
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
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,..){ }}
List View Explained
Entry 1
Entry 2
Entry 3
Entry 4
1
2
3
4
1 Plank No.
PlankPlank
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
Thumbnails in ListView
Common Problem and How to solve it
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
Why is thumbnail such a problem in ListView?
Entry 5
Entry 6
Entry 7
Entry 8
Thread 1Thread 1Now 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
Solution
Entry 1
Entry 2
Entry 3
Entry 4
1
2
3
4Blocking 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
Step 0
1
2
3
4Blocking 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()
Step 1
…..….. Entry 11
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
}
Step 1
Entry 11
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
}
Step 0
3
4Blocking 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
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
Complete Example
• The complete example of the QueuedImageLoader can be found http://code.google.com/p/feedreader/source/browse/trunk/FifaLatestNews/src/com/latestnews/cache/QueuedImageLoader.java
Building Twitter App – Part 2
61
Using Services
Lets see Code Demos for this
Complete Detailed Video of this is available on http://code.google.com/p/droidtwit/wiki/AndroidServiceTutorial
Types of Services
• Main Types– Start Service– Bind Service (using Primitives)– Bind Service (using complex types)– Local Service
63
Using Alarm Manager
Lets see Code Demo
Listener Battery Event
Lets see Code Demo
SQLite Database Demo
Lets see Code Demo
Pull Vs Server Push
• Twitter App is an example of writing Pull Application
• Pull Applications have some drawbacks
67
Drawbacks of DroidTwitt
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
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
Lag
• Notification using Polling will always have a Lag
• It ends up being a balancing act between Saving Battery and Freshness of the data
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?
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.
C2DM Players
Google CloudGoogle Cloud
ApplicationServer
ApplicationServer
But Remember a User can have more than one Device!
Android C2DM to Rescue
Google CloudGoogle Cloud
ApplicationServer
ApplicationServer
Step 1: App Server goes Authentication with Google C2DM Cloud and gets a security token
Security Token
AppServer123
Google CloudGoogle Cloud
ApplicationServer
ApplicationServer
Step 2: Device 1 Registers itself to Google C2DM Cloud, gets an Registration Id
Security Token
AppServer123
Google CloudGoogle Cloud
ApplicationServer
ApplicationServer
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
Google CloudGoogle Cloud
ApplicationServer
ApplicationServer
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
Google CloudGoogle Cloud
ApplicationServer
ApplicationServer
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
Google CloudGoogle Cloud
ApplicationServer
ApplicationServer
Device Info Reg Id
Rohit’s Phone XYZ
Step 7: Device fetches data from App Server to process
Security Token
AppServer123
C2DM Demo
Lets see the Demo
Q & A
91
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