2014-07-02

By the time you read this article, you have likely already been immersed in social media today. In fact, you may have found this article through Facebook, Twitter, the Telerik Developer Portal, Google+, or any number of other networks the cool kids are using these days. Being ‘social’ has taken over the software and hardware industries, encouraging people to share more, more often, and frequently to include media since all our devices are taking pictures and videos – something I never imagined when basking in the glory of an old Polaroid point-n-shoot instant camera growing up in the 80′s. Now things are a lot different – and a lot more complicated!

But with great complication comes great headaches, often referred to as a ‘SDK’. The old hats in the industry knew this as a ‘software development kit’, nowadays it can almost seem like a curse word when thrown into a sentence- “Oh, we were going to release this week but we got SDK’d by a new SharingNetwork release and have to retest all our code because they changed the API again.”

Thankfully, it seems like the powers that be in the software industry have realized this and moved towards a more integrated approach. Since I’m writing this on a Windows 8 machine I can easily swipe in and see the Share charm (are they still calling it that?) that lets me easily share content from an app to any number of services I have installed on the computer. Meanwhile, on my Android HTC One M8, I have a ‘share’ button in apps like the photo gallery that pulls up a similar list of apps that can consume and use my info to do a social post. The nice thing? Photo Gallery doesn’t need to know about SDKs or versions or anything else for Facebook, Twitter, or Google+ – my having them installed on my phone is enough for the integration to happen.

In this article we are going to dive into what it means to ‘socialize’ your app on the Android platform. This will include setting up our application for navigation as well as displaying how you can share both text and photo content from your phone, right from your application. By the time we are finished you will have a solid understanding of how you can easily leverage Android OS features to empower users to share content from your app to whatever network they choose.

Setting Up for Social

Since we’re working on a fresh new Android app, we’ll start this one from File > New Project and build from there. (If you are super-anxious, grab the full source from Github and follow-along!) For more boilerplate items I will use bullet-lists to walk you through steps involved, but for anything more complex I’ll throw a screenshot or two in to help you along.

Before moving forward, make sure you’ve got the latest Android SDK installed, and if you want to follow along complete, I’m using Eclipse and not Android Studio (too new, don’t trust it yet). Right now I’ve got the full API v19 down through v10 installed, since we want version coverage.

To begin, create a new Android Application Project and name it as you see fit. In my version I’m going down to API 10 and up to API 19, but compiled with API 18 (I’ve been having some quirks with v19 on this computer, so I’m being careful with it for now). Everything else is default, so click through until you are staring at a new MainActivity.

Of note – I’ll often use Fragments when working on applications to make it easier to swap between the different layouts and include UI as needed, but since this application is more simplistic I’m cutting all the Fragment code out of the default project setup. If you want to do this as well so your project mirrors mine, do the following:

Remove PlaceholderFragment from the MainActivity file

Remove the if (savedInstanceState… {} section from the onCreate method that references the fragment code

Take all the code from fragment_main.xml and drop it in activity_main.xml, changing the tools:context field to just be .MainActivity

Delete the fragment_main.xml file

You should be able to run the application now and see your app title in the ActionBar as well as the all-too-familiar ‘Hello World’ TextView. Now we’re ready to start socializing.

Start with Text

One of the most universal ways to share something is with a quick message in plain old text. This allows a user to share anywhere from text messages to Twitter without skipping a beat or worrying about how to format their message. With this in mind we’re going to create a ShareTextActivity class (extending android.support.v7.app.ActionBarActivity) with a corresponding activity_share_text.xml layout file (go for LinearLayout). To ensure our new Activity is functional within the application, add a new item to the strings.xml file for our title:

Then go ahead and add our new activity to the manifest:

Take note of the parentActivityName tag as this is going to help us to provide more fluid navigation for users than just relying on ‘hardware’ buttons. I’m going to add a setupActionBar() method to each sub-activity in the application to get the action bar navigation button live and working for our testing, but you can view the code on GitHub to see how it works.

Back in the ShareTextActivity file, populate the onCreate method and use setContentView to designate the activity_share_text.xml layout file as our view. Within that file, add a few descriptive TextView controls to discuss what we are doing as well as an EditText for users to type into. Close out with a button for sharing their text with the world and your layout should be something like so:

We also need to be able to access this from our MainActivity, so add some descriptive text and buttons to the activity_main.xml layout file (I swapped it to LinearLayout for the time being), ensuring that clicking the correct button links to the correct activity (we only have one right now). This will use an Intent for navigation within our application, but in the next section we’ll see an entirely different use for an Intent.

Back into code a bit, within ShareTextActivity we need to set a listener for the onClick event on the share button. We can optionally set a listener on the EditText that both counts characters and accepts an “enter” to submit, but the button works well for our scenario.

When a user clicks the button, we will access the text that was typed in, put that into an Intent, and send that Intent off in the correct format so that different launcher activities can be utilized to share information into the wild. The Intent class is actually built for this, as you can see we are using an explicit Intent.ACTION_SEND as our target and otherwise just ensuring our text is understood by type as well as being placed into the correct extra container:

When we run everything and navigate to the Share Text page, you can type text in and send it off to the OS to handle. In our case, I decided to live dangerously:



Android picked it up with the default application for receiving text/plain messages (which is Messaging), so I sent it as a text to myself:



And a few hardware back-button presses later I’m back to my Share Text activity as if I never had left. Cool, right?

One problem- this forced us to go into the Messaging app. What if I wanted my hashtag seen on Twitter or Facebook? This is a relatively simple fix – instead of just blindly throwing our intent to the OS, we want to provide the user with a chooser to select their preferred method for handling this type of content.

In this case, we’ll want to modify the code above to create a chooser which will provide users the option to select a different program:

Running this on my own phone, you can see all the options for selecting a program to handle this:



Followed by me letting the program handle the intent and providing me with my ‘share’ option, ready-to-go:

And just to prove it was real, my G+:

Fantastic! Now we have the ability to send any arbitrary text to applications that can handle it, but wouldn’t it be nice to share a picture as well?

Sharing a Picture: Challenge Accepted

Despite the theatrics, this really isn’t as complex as you think it might be. Once again create a new ActionBarActivity and also copy over some of the boilerplate code from the ShareTextActivity for setting up the ActionBar. Here is the quick rundown of what we need for the SharePictureActivity:

Create a new SharePictureActivity based on ActionBarActivity

Create a new activity_share_picture.xml layout, based on LinearLayout

StartSharePictureActivity off with the onCreatemethod that also sets the layout to the new one defined above

Add some strings to strings.xml for our Share Pictures title and description

Add a reference to the new activity in the Manifest

Add code in MainActivity to launch the new SharePictureActivity

Now you’re staring at a mostly blank activity for sharing pictures. Sharing a picture is slightly different than sharing text because there are multiple sources pictures can come from (specifically the url pointing to the image or a binary blob with image data), meaning we’ve got to be a little careful with how we bring pictures in.

In our case, sitting in native code and having full access to our phone hardware, we’re going to let users select an image to bring in using another Intent and then push that picture for our sharing. First up we’ll throw up some quick UI to enable this whole picture sharing thing to happen. This will include an ImageView for our thumbnail, a button for opening the camera, and a button for sharing.

My version looks something like this:

Once this is in place, we venture back into the class to pull references to our buttons as well as ImageView. This will enable setting OnClickListener events for both buttons so that our UI will be functional.

Within the OnClickListener for cameraButton, our goal is to provide the user access to the built-in camera to take a picture and then return back to the application. Since we are launching this process with the intention of getting something back, we’ll use startActivityForResult with a corresponding request code integer (this is PHOTO_ID, which I set to 101 for kicks) when launching our intent:

When this returns, we first ensure that the returning result is for the same request code, check for a valid response code, then process the returned intent for use in our activity:

Now we come to the obvious question – we’ve got an intent, what do we do to produce a picture as well as share it out? In our case, we’re actually pretty lucky in that we used MediaStore to produce our picture (making it easier to share than having to create a ContentProvider) and that the camera returns an intent with just the data and extras that we need. The uri location of the picture can be returned by using the intent.getData() method while the bitmap thumbnail of the image is returned via an extra. By accessing the bundle, specifically the “data” extra, we gain access to a bitmap that can be used to populate our thumbnail:

Now that this is all set, we will wire up the Share Picture button to send out the pictureUri to any available applications:

Cool! Now when I use this app, I can share a picture, choose my favorite social media outlet (or messaging, or a photo editing app, etc.), then return right to my app when I’m all finished with the new operation:

Pretty smooth and requires 0% foreign code in my application to enable, just a little knowledge of how the Android OS works.

Sharing is… Free [Marketing]

There are a lot of folks, myself included, who do not fully embrace social media in their day-to-day activities. But when I do hop on Twitter or Facebook or even Google+ it is because I have a reason to be there, and while “sponsored” posts are becoming more common and ignorable, like the banner ads of the social media world, I do respect and value the opinions of actual friends and colleagues.

If I am seeing more and more friends sharing from or using a certain app that greatly increases my chances of checking it out and giving it a spin on my own device, or in the very least engaging in a conversation (possibly on social media) regarding why they are using a given app.

By properly incorporating and integrating social media functionality (“sharing”) into your applications, you empower users to do advertising for you just by using your app. This also enables users to stay connected to their favorite outlets without leaving your application (i.e., users will not have to copy something, leave your app, open a different app, post it, then return), keeping people using your app longer. In an app-centric world, the price of a few lines of code for this type of integration is worth its weight in bytes. If you’ve been following along you now have a great set of examples to help integrate social media sharing in your application, otherwise hop on over to Github for a copy of the code we built today.

The post Social Media Integration on Android appeared first on Telerik Developer Network.

Show more