Blog | jessechen.net

Year 2012 in Review

January 29, 2013 10:00 am by
Jesse Graduation 2012 Newspaper

Most awesome year ever

Would be the shortest way to describe 2012.  It has been a while since the last post, which was an analysis of how the launch of my first Android app InstaWifi went.  For 2013, my resolution is to post more content than in 2012, and to continue to write meaningful and helpful content for android developers as well as some other various random thoughts I may have specifically on tech, entrepreneurship, or on life after college.

In the year 2012, I wrote six posts:

  1. Getting out of the Consumer Mindset - I thought about how much information I consume on a daily basis and it made me aware that I no longer want to solely be a consumer of information but to also be a producer of information.  Since then, I have stopped my addiction with Google Reader, and over the course of the year have become more productive by attending a lot of competitions/hackathons, building cool stuff, and in general, doing a lot more write actions instead of reads.
  2. Protip: Bash Autocomplete for Android ADB - Android development can be a little frustrating at times, but finding little gems such as autocompletion of adb commands, or debugging your app without a cable makes it much better.

  3. Playing the Student Card - I got so much free crap because I was a student that it would be wrong not to share.  Getting a free github micro plan, amazon prime, and discounted Google I/O tickets are some of the most notable ones.

  4. Protip: How to be a Good Boss - This was a more personal post of mine that I wrote to reflect on my experiences being a lead for 3 years for a small technical team.  It’s possible that I don’t actually really know what it’s like to be a good boss, but it’s out there for people to digest.

  5. Freeing Your Online Graduation Pictures - This was a fun tutorial that I co-wrote with Jonathan Tien.  The both of us being CS nerds having just graduated, we wanted to save our grad pictures only to find out they disabled right-click > save as, and put an ugly watermark all over our beautiful bodies.  We weren’t going to have any of that, so we wrote this lengthy, but ultimately useful, tutorial on how to nab those pictures, and to use photoshop to remove the watermark.  It went viral on Facebook and was a huge hit among our class.

  6. Post-hoc Analysis of InstaWifi’s Launch - InstaWifi was my first Android app ever released to the market, and I remember being blown away by the positive reception that I received from the online community. I decided to share with other developers the hard numbers of my launch and some of the reasoning that I put into the app and what worked and what didn’t.

Looking back, I’m happy with the blog posts I’ve written.  My goal for 2013 is to force myself to write more and be more comfortable in my voice in writing.  Also, possibly time to do an entire redesign of this website.

(more…)

Filed under: General — Tags: , , , , , , , — Jesse Chen @ 10:00 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.


Playing the Student Card

March 8, 2012 9:48 pm by
student card

Introduction

One memorable quote I remember from being in Ken Singer’s Mobile Entrepreneurship class is him telling us to always “play the student card”. People enjoy helping students because of a combination of a) its less pressure for them since we don’t work yet (not trying to use them to get a job, or for any other obvious personal gains) and b) they want to help younger folks because they once were in the same situation before as a student. For companies, they want to help us because they want to invest in their brand loyalty toward younger audiences, so that once we have a job and money, we are aware of their company and will continue to use their products.

Turning in my student card

As my years of being a student comes to an end, its time to take a look back and acknowledge the different people and companies that helped me get to where I am now.

  • GitHub
    • As a student studying CS, having a Micros plan on GitHub is invaluable.  A free Micros plan allows you to have up to 5 private repositories with unlimited collaborators.  A must-have for your CS projects and hackathons.
  • Adobe Creative Suite 5
    • Starting in August 2011, all UC Berkeley students gets a free copy of Adobe Creative Suite 5.  Normal price is 379$ for a license (which is out of reach for the 99% of students), so this is a great opportunity for people to learn how to use Photoshop, Fireworks, Illustrator and etc. for their class and personal work.
  • Microsoft Software
    • UC Berkeley students get MS Office and MS operating systems like Windows 7 and XP for free.  Students can barely afford food to eat, who in their right mind would cough up 100$ for a Windows 7 license?  This is a strategic move by Microsoft to ensure that we continue to use their products rather than their competitors.
  • Amazon Prime
    • Back in my day (~2010), Amazon had a promotion for students to have 1-year of Amazon Prime for free (free two-day shipping on all eligible products).  Now, it’s only 6 months but it’s still great.  When my trial expired, I was so spoiled by Amazon Prime service that I renewed my service for 40$/year.
  • Google I/O
    • Every year, Google holds a developer conference to bring thousands of developers for a two (this year, three) day event to network, attend talks, and listen in on the newest products coming from Google. This is a great opportunity for students to get a taste of the real world.  When I first attended Google I/O in 2010, it showed me what computer science is outside of academia, and made me so excited to pursue programming.  That led to me going again in 2011 by the skin of my teeth.  They gave me my first smartphone (my current phone at that time was a Motorola Razr, remember those things?), and since then, I have wrote Android apps, tutorials of many sorts, and have brought me into my passion for mobile.

Now these are services or events that are discounted for students.  The next list is a list of competitions I attended where I played the student card to my advantage.  Younger students take note :)

  • Facebook Mobile Hack
    • Facebook’s Mobile Hack is where you learn how to integrate Facebook services into your mobile app.  At the end, there is a hackathon where you compete for prizes.  I find that when introducing ourselves as “students at UC Berkeley studying CS”, we tend to get more attention that way (since everybody else were working adults).  Take it for what it’s worth, but playing the student card when you are the minority seems to give you an edge.  Not to mention, winning this hackathon got me a job offer.
  • AnDevCon III
    • Playing the student card once again, to try to appeal to the contest organizers.  However, notice there are also several other students playing the student card.  I think perhaps why mine stood out some more was the fact that I was more clear on why I feel like I should go.  Winning a 1,245$ ticket for writing a comment?  Not bad!

Conclusion

Take advantage of the fact that you are a student.  You only have this liberty for 4 years in college before you become a working adult.  The companies, people, and events that you meet and go to love the fact that you are an ambitious student and often times are willing to help one way or another!  For me, I will always be grateful for my student card because it

  • got me my job
  • got me into my career/interest, mobile
  • got me into building apps and competing in more hackathons
  • got me into conferences that I would never be able to afford

The student card is only valid for 4 years.  Use it before it expires.

 

Filed under: General — Tags: , , , , , , , , , , , — Jesse Chen @ 9:48 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.


How to NFC on the Android Platform

August 30, 2011 12:51 pm by
Android and NFC

Introduction

Starting with Android 2.3, the platform includes an NFC stack and framework API that allows you to read/write to NDEF (NFC Forum Data format) tags.  For Android smartphones, that means the requirement is to be running at least Android 2.3 and have a NFC chip on the phone. For iOS, we’ll have to see if the rumors are true that the iPhone 5 is NFC-enabled :).

The only resource I used was the 2011 Google I/O NFC Talk:

and the Sticky Notes demo source code from the NFC talk above.

Let’s pretend that you are an engineer at Facebook working on the Android app, when suddenly the PM tells you that they want to integrate NFC into the Facebook app. Some basic functionality that they want implemented to get started with is to be able to add friends, and check in to places instantly via NFC. This would be a simple way to get started..

(there is no Facebook for Android source code here, I’m writing this tutorial as if we were writing for the app)

P2P Data Transfer – Add Friends Example

Two NFC-enabled devices have the ability to transfer data to each other simultaneously.  For example, two people who just met with NFC-enabled phones can quickly touch their phones together to automatically add each other as friends on Facebook.

To begin, both phones have to be running the same Activity in the foreground in order to work.  Let’s call this Activity ‘NfcAddFriendsActivity’.

In NfcAddFriendsActivity’s onCreate method, we have the following code:

mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0,
    new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// Intent filters for exchanging over p2p.
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
    ndefDetected.addDataType("text/plain");
} catch (MalformedMimeTypeException e) {
}
mNdefExchangeFilters = new IntentFilter[] { ndefDetected };

This sets up the different intents that are needed in order for p2p to work.  mNfcPendingIntent is a generic PendingIntent that will be delivered to this activity, Android fills the intent later with the details from the discovered tag before sending it to this activity.  The nDefDetected IntentFilter is set to filter for the intent NfcAdapter.ACTION_NDEF_DISCOVERED with the mime type “text/plain”.  So there will be a dispatch to the foreground Activity when Android receives an intent matching the IntentFilter we just created.

The next step is to enable pushing NDEF messages and receiving NDEF messages.  That means in our onResume method, we call enableNdefExchangeMode which looks like:

private void enableNdefExchangeMode() {
    mNfcAdapter.enableForegroundNdefPush(NfcAddFriendsActivity.this,
        NfcUtils.getUidAsNdef(mUserId));
    mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, 
        mNdefExchangeFilters, null);
}

These method calls are what allows our device to initiate p2p communiation via NFC.  NfcUtils.getUidAsNdef is the method that creates a NDEF message with mime type “text/plain” with the user’s UID as the payload.  enableForegroundNdefPush will push this message to the other device.  enableForegroundDispatch will set up the listener for the intent that we are filtering for such that when it detects an intent matching the intent filter, it calls our activity’s onNewIntent method:

@Override
protected void onNewIntent(Intent intent) {
    // NDEF exchange mode
    if (!mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        NdefMessage[] msgs = NfcUtils.getNdefMessages(intent);
        fireFriendRequest(msgs[0]);
        Toast.makeText(this, "sent friend request via nfc!", Toast.LENGTH_LONG).show();
    }
}

Here, it parses the received NDEF message and gets the payload which should be the other user’s UID.  Then I call fireFriendRequest which is a method that we can assume sends a friend request to the UID that was given.

NfcUtils.getNdefMessages is below, exactly the same as the Sticky Notes demo:

NdefMessage[] getNdefMessages(Intent intent) {
    // Parse the intent
    NdefMessage[] msgs = null;
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
        || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Parcelable[] rawMsgs = 
            intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        } else {
            // Unknown tag type
            byte[] empty = new byte[] {};
            NdefRecord record = 
                new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
            NdefMessage msg = new NdefMessage(new NdefRecord[] {
                record
            });
            msgs = new NdefMessage[] {
                msg
            };
        }
    } else {
        Log.d(TAG, "Unknown intent.");
        finish();
    }
    return msgs;
}

Writing to a NFC Tag – Checking into Places Example

Let’s create a way for people to check in to places simply by tapping on a NFC tag.  To start, we need to write some data onto a NFC tag, such that when the user taps on the tag, an Activity will launch based on the type of data stored on the tag.  Well, each Facebook “Place” has an id associated with it, so lets write those ids onto NFC tags such that when a user taps on the tag, we can launch the correct Activity, passing the id as a parameter.

Lets assume you have a list of Facebook Places, and when the user clicks on a Place, we prompt them to touch the phone to the tag to write that corresponding Place id onto the tag.  So, when the user taps on a place, onListItemClick is called and this is what happens:

...

Place place = (Place) mListAdapter.getItem(position);

// NFC: Write id to tag
placeidToWrite = place.mPlaceId;
enableTagWriteMode();

new AlertDialog.Builder(NfcWriteCheckinActivity.this).setTitle("Touch tag to write")
    .setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            disableTagWriteMode();
        }
    }).create().show();

...

I hold the placeid in placeidToWrite, and call enableTagWriteMode.  An alert dialog pops up prompting the user to tap the phone to the tag to write.  enableTagWriteMode below:

private void enableTagWriteMode() {
    mWriteMode = true;
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    mWriteTagFilters = new IntentFilter[] { tagDetected };
    mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null);
}

I create a new IntentFilter for the intent NFCAdapter.ACTION_TAG_DISCOVERED, which is the intent to start an Activity when a NFC tag is discovered.  Then, like in the adding friends example, enableForegroundDispatch is called to dispatch a discovered tag to the foreground activity.  Once this is all set up, and the user taps the phone onto a tag, the ACTION_TAG_DISCOVERED intent is detected and onNewIntent is called:

@Override
protected void onNewIntent(Intent intent) {
    // Tag writing mode
    if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (NfcUtils.writeTag(NfcUtils.getPlaceidAsNdef(placeidToWrite), detectedTag)) {
            Toast.makeText(this, "Success: Wrote placeid to nfc tag", Toast.LENGTH_LONG)
                .show();
            NfcUtils.soundNotify(this);
        } else {
            Toast.makeText(this, "Write failed", Toast.LENGTH_LONG).show();
        }
    }
}

NfcUtils.getPlaceidAsNdef takes the placeid and creates a NDEF message with mimetype “application/vnd.facebook.places”, which is a custom and vendor-specific mimetype that I made up to distinguish the different NFC tags (places, url, pages) for Facebook.  That way, when the phone reads a NFC tag, it knows which Activity to launch (I detect mimetype “application/vnd.fb.places” – I should launch this specific Activity from Facebook).

NfcUtils is my handy utility class for all things NFC.  NfcUtils.getPlaceidAsNdef looks like:

/*
* Converts a Long into a NdefMessage in application/vnd.facebook.places MIMEtype.
*
* for writing Places
*/
public static NdefMessage getPlaceidAsNdef(Long id) {
    String msg = ((Long) id).toString();
    byte[] textBytes = msg.getBytes();
    NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
        "application/vnd.facebook.places".getBytes(), new byte[] {}, textBytes);
    return new NdefMessage(new NdefRecord[] { textRecord });
}

Once you construct the NDEF message, you need to actually write it to the tag.  NfcUtils.writeTag looks like:

/*
* Writes an NdefMessage to a NFC tag
*/
public static boolean writeTag(NdefMessage message, Tag tag) {
    int size = message.toByteArray().length;
    try {
        Ndef ndef = Ndef.get(tag);
        if (ndef != null) {
            ndef.connect();
            if (!ndef.isWritable()) {
                return false;
            }
            if (ndef.getMaxSize() < size) {
                return false;
            }
            ndef.writeNdefMessage(message);
            return true;
        } else {
            NdefFormatable format = NdefFormatable.get(tag);
            if (format != null) {
                try {
                    format.connect();
                    format.format(message);
                    return true;
                } catch (IOException e) {
                    return false;
                }
            } else {
                return false;
            }
        }
    } catch (Exception e) {
        return false;
    }
}

And that’s how you write to a tag.  Now, any person with an Android NFC-enabled phone with this build of Facebook for Android would just have to touch their phone onto the sticker (doesn’t need Facebook to be in the foreground), and wham, it takes you straight to the checkin activity with the place already set.

Reading from a NFC tag – Checking into Places Example

Now, we’ll talk about how the phone reads the tag and launch the appropriate Activity.

In the AndroidManifest, we need to write intent-filters that captures the different intents we created with our examples above.  Such that when the Android phone receives the intent, it knows where to pass it along. For checking in, we have an Activity called, lets say, CheckInActivity.  Within the activity, I am going to write an intent-filter that matches the exact intent I created in the NfcWriteCheckinActivity.

This is a snippet of the AndroidManifest for the app:

<activity android:name=".CheckInActivity">
    <intent-filter>
      <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
      <data android:mimeType="application/vnd.facebook.places"/>
      <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

Notice the exact specification of the mimetype, which is the custom vendor mimetype that I created for checking in to places.  That way, I can have one application, like Facebook, pass different intents to different Activities within Facebook.

Within CheckInActivity, it is fairly simple to extract the placeid and open the checkin activity.  You do it in the onResume method of CheckInActivity:

@Override
protected void onResume() {
    super.onResume();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
        NdefMessage[] messages = NfcUtils.getNdefMessages(getIntent());
        byte[] payload = messages[0].getRecords()[0].getPayload();
        String placeId = new String(payload);
        NfcUtils.soundNotify(this);
    }
}

Note: The user ID and the place ID are all written and transmitted in plaintext with no authentication or encryption. FWIW, that may or may not be acceptable for some apps. I haven’t looked into the security implications on NFC, but if you are passing confidential data, you will have to find a way to encrypt the data before writing, verifying the integrity of the data when receiving, and authenticating the entity that sent the data. Since this was a personal hackathon project, I did not implement any security features.

Background

Last semester, I was in IEOR 171 – Technology Leadership which is a course where you form small groups to hypothesize and analyze an industry change in the next ten years.  During the beginning of the semester was around the time when Google’s mobile payment service via NFC was leaked, as well as when Gingerbread (Android 2.3) was announced, which is the first version of Android that includes an NFC stack.  It was the first time I heard of NFC and I thought that it had tremendous potential for different applications on mobile phones.  So I proposed to my group that we research the potential for NFC technology in the United States for the next ten years in the United States.  My group was enthusiastic about it, and you can read our final paper in the IEOR 171 section.

Last summer, I interned at Facebook and one of the best things about working there are the hackathons – all night coding sessions with beer, music, and takeout food where you can work on a team or by yourself to build a product out of an idea.  Being excited about NFC (see above), I decided to integrate NFC technology into the Facebook for Android app as a personal hackathon project.  Overnight, I was able to have a working build of the Facebook app where you can add friends, check in to places, share URLs, and go to a Page via NFC.

I pitched my hackathon project to the Product Managers, Directors, and even Zuck himself (emailed him some demos but he didn’t respond haha).  They all said that it was awesome but the problem was not enough NFC-enabled phones in the market – so unfortunately, it is not happening.

I didn’t want all that work to be wasted, so this is a tutorial on how to integrate NFC technology on the Android platform in hopes that people can use it to build cool applications that uses NFC!

You can also read about my second hackathon project, implementing Google Plus’s Instant Upload feature on Facebook.

Do you enjoy reading my posts? Subscribe to me on Facebook below to stay updated!

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.