92
Building Twitter App Rohit Ghatol

Salt march 2011-building twitter app

Embed Size (px)

DESCRIPTION

Salt march 2011-building twitter app

Citation preview

Page 1: Salt march 2011-building twitter app

Building Twitter App

Rohit Ghatol

Page 2: Salt march 2011-building twitter app

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

Page 3: Salt march 2011-building twitter app

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

Page 4: Salt march 2011-building twitter app

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

Page 5: Salt march 2011-building twitter app

Building Twitter App – Part 1

5

Page 6: Salt march 2011-building twitter app

Twitter App Demo

http://code.google.com/p/DroidTwitt

Page 7: Salt march 2011-building twitter app

Youtube Video Demo

• http://www.youtube.com/user/rohitssghatol#p/u/13/XhCZpxWDtx0

Page 8: Salt march 2011-building twitter app

Twitter Requirements

OAuth Authentication

OAuth AuthenticationFetch TweetsFetch Tweets

Send TweetsSend Tweets

Background SyncBackground Sync

Page 9: Salt march 2011-building twitter app

Overall Architecture

Page 10: Salt march 2011-building twitter app
Page 11: Salt march 2011-building twitter app

OAuth Authentication

Page 12: Salt march 2011-building twitter app
Page 13: Salt march 2011-building twitter app

First Time Launch

Page 14: Salt march 2011-building twitter app
Page 15: Salt march 2011-building twitter app

Asking Service To Fetch Tweets

Page 16: Salt march 2011-building twitter app
Page 17: Salt march 2011-building twitter app

Triggering Service every n minutes

Page 18: Salt march 2011-building twitter app
Page 19: Salt march 2011-building twitter app

Phone Boot Event

Page 20: Salt march 2011-building twitter app
Page 21: Salt march 2011-building twitter app

Battery Low Event

Page 22: Salt march 2011-building twitter app
Page 23: Salt march 2011-building twitter app

OAuth

Short Introduction to OAuth

Page 24: Salt march 2011-building twitter app

http://fotofast.comhttp://fotofast.com

username

password

LoginLogin CancelCancel

http://fotofast.comhttp://fotofast.comWelcome Rohit

Picasa Flickr

Print PhotoPrint Photo

Page 25: Salt march 2011-building twitter app

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?

Page 26: Salt march 2011-building twitter app

Take 2, Action

Page 27: Salt march 2011-building twitter app

http://fotofast.comhttp://fotofast.com

username

password

LoginLogin CancelCancel

http://fotofast.comhttp://fotofast.comWelcome Rohit

Picasa Flickr

Print PhotoPrint Photo

Page 28: Salt march 2011-building twitter app

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

Page 29: Salt march 2011-building twitter app

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

Page 30: Salt march 2011-building twitter app

Twitter OAuth in Android

Page 31: Salt march 2011-building twitter app

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

Page 32: Salt march 2011-building twitter app

How does the same work for Android Applications?

Page 33: Salt march 2011-building twitter app

Steps of Twitter OAuth

Page 34: Salt march 2011-building twitter app

Step 1 : Register with Twitter for OAuth Token

Page 35: Salt march 2011-building twitter app
Page 36: Salt march 2011-building twitter app

Step 2: Register your Activity to handle url “DroidTwit://twitt”

Page 37: Salt march 2011-building twitter app

<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>

Page 38: Salt march 2011-building twitter app

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

Page 39: Salt march 2011-building twitter app

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())));}

Page 40: Salt march 2011-building twitter app

Step 4: Handle Response from Browser after OAuth

Page 41: Salt march 2011-building twitter app

@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]);}

}

Page 42: Salt march 2011-building twitter app
Page 43: Salt march 2011-building twitter app

For more details on OAuth in Android read

http://blog.copyninja.info/2010/09/android-oauth-authentication-with.html

Page 44: Salt march 2011-building twitter app

Fetching From Twitter API

Page 45: Salt march 2011-building twitter app

Guidelines

• Make the fetch module SynchronousList<Tweets> getLatestTweets();

• Either call directly or through Services

• Use AsyncTask on UI to avoid ANR

Page 46: Salt march 2011-building twitter app

ListView Showing Tweets

Lets see a some code for this.

http://code.google.com/p/droidtwit/wiki/AndroidListActivityAsyncTaskTutorial

Page 47: Salt march 2011-building twitter app

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

Page 48: Salt march 2011-building twitter app

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,..){ }}

Page 49: Salt march 2011-building twitter app

List View Explained

Entry 1

Entry 2

Entry 3

Entry 4

1

2

3

4

1 Plank No.

PlankPlank

Page 50: Salt march 2011-building twitter app

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

Page 51: Salt march 2011-building twitter app

Thumbnails in ListView

Common Problem and How to solve it

Page 52: Salt march 2011-building twitter app

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

Page 53: Salt march 2011-building twitter app

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

Page 54: Salt march 2011-building twitter app

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

Page 55: Salt march 2011-building twitter app

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()

Page 56: Salt march 2011-building twitter app

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

}

Page 57: Salt march 2011-building twitter app

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

}

Page 58: Salt march 2011-building twitter app

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

Page 59: Salt march 2011-building twitter app

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

Page 60: Salt march 2011-building twitter app

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

Page 61: Salt march 2011-building twitter app

Building Twitter App – Part 2

61

Page 62: Salt march 2011-building twitter app

Using Services

Lets see Code Demos for this

Complete Detailed Video of this is available on http://code.google.com/p/droidtwit/wiki/AndroidServiceTutorial

Page 63: Salt march 2011-building twitter app

Types of Services

• Main Types– Start Service– Bind Service (using Primitives)– Bind Service (using complex types)– Local Service

63

Page 64: Salt march 2011-building twitter app

Using Alarm Manager

Lets see Code Demo

Page 65: Salt march 2011-building twitter app

Listener Battery Event

Lets see Code Demo

Page 66: Salt march 2011-building twitter app

SQLite Database Demo

Lets see Code Demo

Page 67: Salt march 2011-building twitter app

Pull Vs Server Push

• Twitter App is an example of writing Pull Application

• Pull Applications have some drawbacks

67

Page 68: Salt march 2011-building twitter app

Drawbacks of DroidTwitt

Page 69: Salt march 2011-building twitter app

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

Page 70: Salt march 2011-building twitter app

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

Page 71: Salt march 2011-building twitter app

Lag

• Notification using Polling will always have a Lag

• It ends up being a balancing act between Saving Battery and Freshness of the data

Page 72: Salt march 2011-building twitter app

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?

Page 73: Salt march 2011-building twitter app

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.

Page 74: Salt march 2011-building twitter app

C2DM Players

Page 75: Salt march 2011-building twitter app

Google CloudGoogle Cloud

ApplicationServer

ApplicationServer

But Remember a User can have more than one Device!

Page 76: Salt march 2011-building twitter app

Android C2DM to Rescue

Page 77: Salt march 2011-building twitter app

Google CloudGoogle Cloud

ApplicationServer

ApplicationServer

Step 1: App Server goes Authentication with Google C2DM Cloud and gets a security token

Security Token

AppServer123

Page 78: Salt march 2011-building twitter app

Google CloudGoogle Cloud

ApplicationServer

ApplicationServer

Step 2: Device 1 Registers itself to Google C2DM Cloud, gets an Registration Id

Security Token

AppServer123

Page 79: Salt march 2011-building twitter app

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

Page 80: Salt march 2011-building twitter app

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

Page 81: Salt march 2011-building twitter app

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

Page 82: Salt march 2011-building twitter app

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

Page 83: Salt march 2011-building twitter app

C2DM Demo

Lets see the Demo

Page 84: Salt march 2011-building twitter app
Page 85: Salt march 2011-building twitter app
Page 86: Salt march 2011-building twitter app
Page 87: Salt march 2011-building twitter app
Page 88: Salt march 2011-building twitter app
Page 89: Salt march 2011-building twitter app
Page 90: Salt march 2011-building twitter app
Page 91: Salt march 2011-building twitter app

Q & A

91

Page 92: Salt march 2011-building twitter app

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