Blog | jessechen.net

How Does Google Plus Instant Upload Work?

August 18, 2011 5:13 pm by

Introduction

When I first heard about Google Plus and their Instant Upload feature, my initial thought was “how does this work?”.  I did a quick search on Google to see if there were any other people who were curious about how they do it.  I found only one useful result, this stack overflow post (stack overflow has been invaluable this summer), and it got me thinking about how cool it would be to try to do the same thing.  The words ContentProvider and ContentObserver was gibberish to me but I dedicated one night to see if I can figure this thing out.  Turned out, it was actually quite easy and not that hard to understand.

This is probably not the exact way that Google+ used to implement Instant Uploads, but it provides the same functionality, with a bonus that Google+ does not have – that it’ll work with any camera app, not just the native camera app.  My hope is that this tutorial will help others that may be curious about how to do something similar.

Content Providers are the only way to share data across different applications.  They can store and read data, and Android has a bunch of content providers already provided for you for common data types, such as video, audio, images and contacts.

Content Observers are just that.  It’s an abstract class that has a method that gets called when it observes a change in a content provider.

Hopefully you figured out now that what we simply have to do is register a content observer to the images content provider.

InstantUploadActivity

Let’s create a simple and useless Android project that will detect when a picture is taken and display the most recent picture’s file name in a TextView.  The content provider that we want to observe is the one that Android provides for images, and the URI for that is MediaStore.Images.Media.EXTERNAL_CONTENT_URI.

We start with the onCreate method in the Activity:

public class InstantuploadActivity extends Activity {

    private PhotosObserver instUploadObserver = new PhotosObserver();
    private String saved;
    private TextView tv;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView)findViewById(R.id.textview);

        this.getApplicationContext()
            .getContentResolver()
            .registerContentObserver(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, false,
                instUploadObserver);
        Log.d("INSTANT", "registered content observer");
}

Upon creation of this Activity, we register our custom PhotosObserver (which extends ContentObserver) to the images content provider.

Recall that the goal for this project is to simply take the most recent picture’s file name and display it in our Activity’s TextView, tv.  To get alerted when a new picture is taken, we have to create a class that extends ContentObserver and implement the onChange method:

private class PhotosObserver extends ContentObserver {

    public PhotosObserver() {
        super(null);
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Media media = readFromMediaStore(getApplicationContext(),
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        saved = "I detected " + media.file.getName();
        Log.d("INSTANT", "detected picture");
    }
}

private Media readFromMediaStore(Context context, Uri uri) {
    Cursor cursor = context.getContentResolver().query(uri, null, null,
        null, "date_added DESC");
    Media media = null;
    if (cursor.moveToNext()) {
        int dataColumn = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        String filePath = cursor.getString(dataColumn);
        int mimeTypeColumn = cursor
            .getColumnIndexOrThrow(MediaColumns.MIME_TYPE);
        String mimeType = cursor.getString(mimeTypeColumn);
        media = new Media(new File(filePath), mimeType);
    }
    cursor.close();
    return media;
}

private class Media {
    private File file;
    @SuppressWarnings("unused")
    private String type;

    public Media(File file, String type) {
        this.file = file;
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public File getFile() {
        return file;
    }
}

In the onChange method we call readFromMediaStore, which will retrieve data about the most recent picture (the one that was just taken). readFromMediaStore initializes a Cursor on the same Images URI that we’ve been observing.  We then grab the filepath and the filetype from the first result (note: the cursor was sorted by “date_added DESC”) and create a new Media to return.  Keep in mind that this can be done when our Activity is not running in the foreground.  You can launch InstantUploadActivity, press “Home” to back out, then go to Camera and take a picture – and the onChange method will still get called.

From here, we simply set the String variable saved to display the filename such that when you go back to the Activity, the filename of the picture you have just taken is displayed in the TextView via the onResume method:

@Override
public void onResume() {
    super.onResume();
    if (saved != null) {
        tv.setText(saved);
    }
}

Lastly, don’t forget to unregister the content observer if onDestroy is called:

@Override
public void onDestroy() {
    super.onDestroy();
    this.getApplicationContext().getContentResolver()
            .unregisterContentObserver(instUploadObserver);
    Log.d("INSTANT", "unregistered content observer");
}

You can do much better than just setting text on a TextView.  You can take that image and resize it, and then upload it somewhere, or you can automatically apply an image filter on each picture or do both!  There are many cool things you can do with this.

Check out the full source code on github here.

Conclusion

This was my second hackathon project at Facebook, and I was able to implement this functionality into the Android Facebook app successfully such that whenever you took a picture from any camera app, it would get uploaded to your Mobile Uploads album.  Instead of storing the filepath of the most recent picture like in the example above, I grabbed the URI of the picture that was just taken and sent it to an upload service in the Facebook app that took care of uploading the picture to your album.  I also built some preferences so that you can enable or disable it depending on if you’re connected to wifi, roaming, or charging your phone.

Unfortunately, my hackathon project is not going to be implemented but it was a fun learning experience.  It is also hard to describe the utter excitement when seeing this work for the first time at 5am, having a picture taken from your camera and onto Facebook in a matter of seconds.  Stay tuned for another tutorial on another hackathon project!

EDIT: And here it is: How to NFC on Android

Filed under: Android,How to — Tags: , , , , , , , — Jesse Chen @ 5:13 PM

About

Jesse is a software engineer at Facebook, who just graduated from UC Berkeley. Passionate about mobile technology and entrepreneurship, he started his own blog as a home for his tutorials, projects, and random thoughts. Follow him on Facebook to stay updated on his latest tutorials and projects.


Facebook Messenger – Why You Should Use It

August 9, 2011 11:42 am by

Today, Facebook announced a new standalone-app called Facebook Messenger.  Tech-savvy users might have heard of WhatsApp or Beluga (which was bought by Facebook to create Facebook Messenger), which are mobile messaging apps that Facebook Messenger will eventually replace.  This app is killer because it essentially replaces SMS and all other forms of mobile communication.

So what’s the big deal?  Why should I use it?

Some of you might be wondering what the heck is Facebook Messenger, and why you should or should not use it.  This article is here to help you understand it better and why you might want to try it out — and if you feel like this article might help others, feel free to recommend it to your friends up top ;P.  The download links are at the bottom.

Facebook Messenger makes it extremely easy to communicate with your friends on a mobile device.  Think about the other alternatives that you might be currently using: Google Talk, it works well with other people who have Android devices since Talk is installed on every Android device, but you need to find and add buddies.  SMS, bad but works if you have their phone number, unfortunately, it costs money for a SMS plan and not very useful (can’t specify location or group chat).  WhatsApp, decent because it works on any device but you need to convince your friends to install WhatsApp.  BBM/iMessage: Platform-specific, can’t be used by everyone.  The current choices out there have common lacking functionality that Facebook Messenger addresses.

1. Message anyone that is your friend on Facebook, as well as your phonebook contacts

Some of the people that I can message via Facebook MessengerThe common problem in GTalk and every other mobile messaging app is the lack of friends.  You have to proactively reach out to others to find out if they use the same service as you, and then add them in order to begin using their product.  I used GTalk prior to Facebook Messenger, and it is great for communicating only with my closest friends that use Android.  However, it becomes difficult when I want to message other people who don’t fit that category.

With Messenger, you won’t have to ask somebody for their phone number or their screen name — as long as you are friends on Facebook, you can instantly message them.  As you can see in the screenshot, Messenger lets me communicate with any of my friends instantly without having to worry about whether they have text, or if they have this app or not.  It ignores all platform barriers (Android/iOS/RIM/etc) and thus, makes it possible to connect with anybody with a mobile device.  I would say this is the number one feature, which is the ability to message anybody that you are friends with on Facebook instantly.

2. SMS Integration 

send SMS from Facebook MessengerFacebook Messenger is going to kill SMS as the primary form of mobile messaging.  It really does not make sense to pay for a SMS plan anymore.  We all know (or at least should know) that carriers pay virtually nothing for text messages and it is an extremely archaic way to communicate with somebody (140-char limit, and no rich media integration such as pictures or location).

In this screenshot, you can see that I have the choice between sending the message to her mobile number, or to her inbox 0n facebook.com.  If the people you message use Facebook Messenger, then they will instantly receive a push notification on their phone when you send them a message.  If you message someone who does not have Facebook Messenger on their mobile device, then you can send the message via SMS for free, as long as their number is supported (you can’t send to some international carriers).  I think it’s really important to note that last part when you are able to send texts for free.

 

3. Location and Photo Sharing

Sharing your location via Facebook MessengerHow many times have you wanted to tell somebody where you are when trying to meet via texts?  I remember reading this reddit post a while back and sharing the hivemind’s sentiment, “Why don’t we have something like this already?”.  Sharing a map view is such a useful feature to have when trying to coordinate a place to meet and Facebook Messenger allows you to do just that.  If you share your location, friends can view a map that they can then search how to find directions to your current location.  I love how Facebook Messenger’s arrow icon is almost exactly the same as the image link in the reddit post, it’s almost as if they reddit themselves and listened to the hivemind.  As usual, you can turn off location sharing for all messages as well as on a per message and per thread basis.  Attaching photos is also nice, good for quickly sharing pictures taken on your phone with someone…or a group of people.

4. Group Chat

Chat with multiple people using Facebook MessengerNot much that needs to be said.  There has definitely been times when I had to use SMS to communicate with multiple people and it was laughably pathetic.  It was like playing telephone.  With group chat, everyone can stay synced and it makes coordinating and planning easier, especially when you use group chat with number 3.

 

Conclusion

I have been using it for a few weeks now (internal dogfooding ftw), and it is quite solid for a version 1.  I have chosen Facebook Messenger already as my default for mobile messaging.  Sure, on occasion, I’ll still use GTalk and sometimes Google Voice for texting, but if I can convince my closest friends to use Facebook Messenger, then there will be no reason to use any other service.  I can instantly message them, attach pictures as well as share my location, and also start group conversations to communicate with multiple people.

However, there are still some things I don’t like about it.  For example, although I can send SMS to most of my friends, for those I have convinced to use Google Voice entirely for texting, I am not able to since it doesn’t support sending SMS to Google Voice numbers.  When I tried sending a text to a Google Voice user, an error message pops up but it is not apparent to me that it doesn’t work because Messenger doesn’t support his carrier.  And if I can’t send to his mobile number, then why can’t I select the option to send a Facebook message instead?  Also, a nitpick is when creating a new conversation, it is difficult to understand what the mobile icon next to their name meant.  As of now, I believe it means it’ll be sent to their mobile phone.  Lastly, for some people, having more customizable alert muting options also would be more useful.

A few weeks ago, during the Skype Video integration launch, Mark Zuckerberg said that “this is possible because the social infrastructure exists, the system knows we’re connected and we have the pipe open between us so new applications can flow between us”.  Facebook is at a very strategic advantage where they have something that no other company has, and that is your social graph.  With that “social infrastructure” in place, applications that use Facebook will inherently be better than the ones that don’t.  Facebook Messenger is an excellent example where it is already better than the current options out in the market right now because it is built on top of your social network.

[Android Market link][iPhone App Store link]

Filed under: General,Reviews — Tags: , , , , , , , — Jesse Chen @ 11:42 AM

About

Jesse is a software engineer at Facebook, who just graduated from UC Berkeley. Passionate about mobile technology and entrepreneurship, he started his own blog as a home for his tutorials, projects, and random thoughts. Follow him on Facebook to stay updated on his latest tutorials and projects.


Summer of 2011 – Google I/O and Facebook

June 9, 2011 11:45 pm by

I don’t know how to describe the past month other than the word ‘crazy’.  So much has happened during this past month that I found sufficient reason to write it down such that I can step back and assess it and lay out my plans for this summer.

So what happened this past month?

In April, I wrote about how I actually was still able to go to Google I/O despite not being able to buy a ticket.  Well, Google I/O 2011 was nothing short of amazing.  They had plenty of exciting announcements to excite all 5,000 developers that attended such as Google Music, Movies, and Chromebooks to name a few.  Not to mention that every attendee received a limited-edition Samsung Galaxy Tab 10.1, Verizon 4G Mobile Hotspot (+ 3 month service), and a Chromebook in the near future.  It seems like every year they take it to another level.  Many people joked that in a few years each person will get a free self-driving car.

Even though Google I/O was during finals week and I sacrificed a ton of studying time for it, it was definitely worth it.  After school was over, I went to China for 3 weeks to visit Konnie and my relatives, whom I haven’t seen for about 6 years.  It was a very special opportunity to go back to the motherland and visit my old relatives and polish my Mandarin a little bit.  Everyone said I’m not chubby anymore, which is a good thing I suppose..

So what now?

I started working at Facebook this week.  What I’m doing there is serving as the Analytics guy on one of the Marketing teams.  So over the course of my summer, I’ll be developing/upgrading internal tools for my team that will hopefully simplify and streamline their work process.

Facebook treats their employees, including the interns, extremely well.  All the people I’ve met so far are awesome people who are super gosu at what they do.  Not to mention that they are genuinely passionate in the work they do and it inspires me to be the same.  My goal for this summer at Facebook is to produce results by the end as well as getting a better understanding of what kind of career path I should be heading towards.

Conclusion

Lastly, putting this out in public so I will stay committed.  This summer, my three priorities are: work, android app, and basketball/gym.

Work: Work hard at Facebook, move fast, break things, and get stuff done.

Android app: Integrate server code and updates from server, finalize any additional features to add, polish UI – all done by Fall 2011.

Gym/Basketball: Play ball 2-3 times every week, work out 3 days a week (squats, deadlifts, benchpress and power cleans).

Filed under: General — Tags: , , , , , , , — Jesse Chen @ 11:45 PM

About

Jesse is a software engineer at Facebook, who just graduated from UC Berkeley. Passionate about mobile technology and entrepreneurship, he started his own blog as a home for his tutorials, projects, and random thoughts. Follow him on Facebook to stay updated on his latest tutorials and projects.