Posts

Android Intents Tutorial to Share Your Social Media Links

The following Android intents tutorial will help increase your app’s Facebook likes or twitter followers. Almost every app has their own social media accounts or links that you can like, follow, +1, or even send an email to. There’s always an app that can connect you to that product or service.

Android Intents Tutorial to Share Your Social Media Links

Now, from that app, a user must be able to view your accounts effortlessly and in a standard, native and beautiful way. Don’t just throw a browser with a link to a social media account, impress your users by opening it in the native app! The most commonly used social media apps are Facebook, Twitter and Google Plus.

Those are covered in this post, but with the additional Browser and GMail intents! For this code’s demo, see our Android Intents video demo below.

Video Demo Permalink

DOWNLOAD APP

By the way, the app on the demo above is this blog’s official browser app. You might want to download it on Google Play. I didn’t have enough time to develop that app due to my busy schedule. But it is working fine, try it out!

Contents:

1.0 Facebook Intent in Android
2.0 Google Plus Intent in Android
3.0 Twitter Intent in Android
4.0 Browser Intent in Android
5.0 GMail Intent in Android
6.0 How to Check If An App Is Installed in Android?

1.0 Facebook Intent in Android

Here’s how my app show that Facebook page.
Step 1: Go to the FB page and get the Facebook page name using the URL, in my case, it is “CodeOfANinja”
https://www.facebook.com/CodeOfANinja
You can also get the Facebook page ID using the graph API URL, for example
http://graph.facebook.com/CodeOfANinja
…and see the “id”: “107786425949934″ on that JSON string.

Step 2: Use the method below on your Listener, just replace the Facebook page name or ID. You can also use some parameters on this method if you’re opening multiple Facebook pages.

public void openFacebookPage() {
Intent i = null;

try {
context.getPackageManager().getPackageInfo(“com.facebook.katana”, 0);

// replace 107786425949934 with your page ID
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“fb://profile/107786425949934″));

} catch (Exception e) {

// replace CodeOfANinja with your page name
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“https://www.facebook.com/CodeOfANinja”));
}

checkIfAppExists(i, “Facebook”);

}

2.0 Google Plus Intent in Android

Calling the official Google Plus app to show the Google+ page of your customers would be great. That’s one feature I already worked with and now I’m ready to show you the working code I used.
Here’s how I did it:
Step 1: Go to the Google+ Page and copy the page ID. In my case, it is: 101266899643014043497
https://plus.google.com/101266899643014043497/posts

Step 2: Add the following code in your file or utility class.

public void openGooglePlusPage(String googlePlusId){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setClassName(“com.google.android.apps.plus”, “com.google.android.apps.plus.phone.UrlGatewayActivity”);
i.putExtra(“customAppUri”, googlePlusId);
startActivity(i);

checkIfAppExists(i, “Google Plus”);
}

How to use? Just call the function with the ID you got in step 1.

openGooglePlusPage("101266899643014043497");

3.0 Twitter Intent in Android

Here’s how my app show that Twitter page.
Step 1: Get the Twitter page username, in my case, it is “ninjazhai”
https://twitter.com/ninjazhai

Step 2: Add the following method on your project or utility class.

public void openTwitterPage(String username){
Intent i = null;

try {

// use the twitter app
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“twitter://user?screen_name=” + username));

}catch (Exception e) {

// try to use other intent
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“https://twitter.com/#!/” + username));
}

checkIfAppExists(i, “Twitter”);
}

How to use the method above? Remember the twitter username you got on step 1 and put code below on your click listener:

openTwitterPage("ninjazhai");

4.0 Browser Intent in Android

This time we are going to take a look at the browser intent filter in android. I used this one when I want my users have the ability to view the subscribe form of this blog. This code basically answers the question “How do I show a web page from my app to a web browser?”
Here’s the working code I used. Just follow this two step guide.
Step 1: Of course, prepare the URL you wanted to be shown. In my case, it was:
http://feedburner.google.com/fb/a/mailverify?uri=TheCodeOfANinja

Step 2: Add this method to your JAVA file or utility class.

public void openUrl_InBrowser(String url){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));

checkIfAppExists(i, “Web Browser”);

}

How to use? easy, you can do it this way.

openUrl_InBrowser("http://feedburner.google.com/fb/a/mailverify?uri=TheCodeOfANinja");

5.0 Gmail Intent in Android

You can use this code when you want your users to have the ability to send email from your app, for example is the app feature where the users can send feedback, comments or suggestions directly to any given email address.

This code will open the Gmail App with the help of android intent filter.

Now you can add this code to your project or utility class.

public void openGmailApp(String[] emailAddresses, String subject, String text){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setType(“plain/text”);
i.setClassName(“com.google.android.gm”, “com.google.android.gm.ComposeActivityGmail”);
i.putExtra(Intent.EXTRA_EMAIL, emailAddresses);
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, text);
checkIfAppExists(i, “Gmail”);

}

And you can use the method above this way:

// you can try to add more email in this array: new String[] { "ninjazhai30@gmail.com", "email2@yahoo.com" }
// if you're going to send the message to multiple people
openGmailApp(
new String[] { “ninjazhai30@gmail.com” },
“Feedback for The Code of a Ninja Programming Blog”,
“Sent using The Code of a Ninja Android App:nn“
);

6.0 How to Check If An App Is Installed in Android?

Before a specific app will run, we have to verify if that app exists or installed in the device. This will enable us to tell the user that a certain app must be installed before using a feature. This prevents showing an error or force close message, so it is good for the user experience. The method below will show us the way.

Checking if an app is installed in the Android device is required if you are going to start another applications’s intent. There are other ways to do this but the code below is what’s working for me.

I used and tested this code when I wanted to start an intent to some apps like:

  • Facebook
  • Twitter
  • Google Plus
  • Browser
  • Gmail
// method to check whether an app exists or not
public void checkIfAppExists(Intent appIntent, String appName){

if (appIntent.resolveActivity(context.getPackageManager()) != null) {

// start the activity if the app exists in the system
startActivity(appIntent);

} else {

// tell the user the app does not exist
Toast.makeText(context, appName + ” app does not exist!”, Toast.LENGTH_LONG).show();
}
}

Sample Usage: Below is the code I used when I want to open my google plus page with the Google+ official android app.

Intent i = new Intent(Intent.ACTION_VIEW);
i.setClassName("com.google.android.apps.plus", "com.google.android.apps.plus.phone.UrlGatewayActivity");
i.putExtra("customAppUri", "101266899643014043497");
startActivity(i);
checkIfAppExists(i, “Google Plus”);

You can read more about Android intents here.

Simple Android JSON Parser Example Code with URL and Logcat Output

android json parser example

Today I’m going to share an Android JSON Parser example code to parse a JSON string from a URL.

This code is really useful because nowadays, JSON string is being used by most APIs like Facebook graph API and Google Maps.

You should use JSON in your projects instead of XML because it is lightweight, so much easier to parse, and is supported by most programming language.

Recently, I wrote about how to generate JSON string with PHP which can be useful for you too.

But if you really have to use XML, you can also take a look at my older post: Parse XML in Android With Three Input Sources

DOWNLOAD SOURCE CODE

We will cover the following contents in this post:

1.0 Creating JSON String
2.0 Creating our JSON Parser Class
3.0 Using JSON Parser Class with JSON String
4.0 Logcat Output
5.0 Online Resources

1.0 Creating JSON String

Create a JSON string and make it accessible via URL. I created an example for this post, you can see it in this URL: http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php

What it looks like in a JSON viewer:

android-json-parser-example-json-string

As for the code on how to create that JSON string, you can take a look at my older post: Generating JSON String with PHP

2.0 Create our JSON Parser Class

You can use this JSON parser class with any of your JSON string from URL. Here’s our JsonParser.java:

package com.example.androidjsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JsonParser {

    final String TAG = "JsonParser.java";

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONObject getJSONFromUrl(String url) {

        // make HTTP request
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();

        } catch (Exception e) {
            Log.e(TAG, "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e(TAG, "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

3.0 Using JSON Parser Class with JSON String

Now we want to make use of our JSON parser with the generated JSON string from URL. But before running our code, make sure you enable internet permission in your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Now take a look at our MainActivity.java:

package com.example.androidjsonparsing;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // we will using AsyncTask during parsing 
        new AsyncTaskParseJson().execute();
    }

    // you can make this class as another java file so it will be separated from your main activity.
    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

        final String TAG = "AsyncTaskParseJson.java";

        // set your json string url here
        String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";

        // contacts JSONArray
        JSONArray dataJsonArr = null;

        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... arg0) {

            try {

                // instantiate our json parser
                JsonParser jParser = new JsonParser();

                // get json string from url
                JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

                // get the array of users
                dataJsonArr = json.getJSONArray("Users");

                // loop through all users
                for (int i = 0; i < dataJsonArr.length(); i++) {

                    JSONObject c = dataJsonArr.getJSONObject(i);

                    // Storing each json item in variable
                    String firstname = c.getString("firstname");
                    String lastname = c.getString("lastname");
                    String username = c.getString("username");

                    // show the values in our logcat
                    Log.e(TAG, "firstname: " + firstname 
                            + ", lastname: " + lastname
                            + ", username: " + username);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {}
    }
}

4.0 Android JSON Parser Example Logcat Output

It is important for us to see the extracted data from the JSON string or URL. So here’s the logcat output of our code for today.

android-json-parsing-tutoril

5.0 Online Resources

I think the following online resources can also help you in doing such tasks. Check them out!

How to parse JSON in Android?
Android JSON Reader

If you have any other solutions or comments to improve this Android JSON parser example code, please let us know in the comments section below. Thanks for reading our code tutorial!

Fixed: Android Dependencies – Missing facebooksdk.jar

Recently I was working with the Facebook SDK for Android and found the error:     Android     Dependencies     –     Missing     facebooksdk.jar. My project was unable to run and the eclipse console or logcat does not give a clear description of the error.

Home>Android Fixed: Android Dependencies – Missing facebooksdk.jar

But it can be seen when you try to view the properties > java build path > libraries tab > android dependencies of your project.
It looks like the project is looking for the facebooksdk.jar in the Facebook SDK bin folder. But it was missing. I wasn’t able to found a fix after around 30 minutes of googling the error. I don’t know, maybe my google skills are just failing me.
But the good thing is I was able to fixed this error myself. And here is the solution:

Right click on your project > properties > java compiler > compiler compliance level > select 1.7 on the dropdown.

Wait for a while while eclipse re-builds the workspace. Suddenly it was fixed!
Sorry I was too lazy to put up some screenshots, this is just a quick post that I thought can be useful to some devs. As always, thanks for reading!

Introducing The Code Of A Ninja’s Android App (Beta)

Introducing our favorite programming blog’s android app! For the past few days, I have some spare time to code this. Now you guys can browse our blog instantly in your Android phone or tablet. To download this free app, go to your Google Play store and then search using the keywords “code blog by mike dalisay“, you can see our app on the search result.

0-codeofaninja-android-app-search

I think the first advantage of having a mobile website android app is, an app has to be installed. It means that your website or blog will have its own program and icon in the device home screen or list of apps. Users can put it anywhere they want. Our awesome readers can simply tap it to instantly visit your site and see some updates.

The app (ninja) icon is in my home screen.

The app (ninja) icon is in my home screen.

As for the features of this app, we’ll have screenshots with captions below, this can also be a user’s guide.

The Blog View or the “Read Codes” section.  Launching the app will bring you here.

The Blog View or the “Read Codes” section.
Launching the app will bring you here.

The Navigation Drawer. You can see this view if you click the  ninja icon on the upper left corner OR did a swipe from left to right.

The Navigation Drawer. You can see this view if you click the
ninja icon on the upper left corner OR did a swipe from left to right.

Tapping the “About Blog” option will  show you some info about the blog.

Tapping the “About Blog” option will
show you some info about the blog.

“The Ninjas” section contains some information  about the people behind our blog.

“The Ninjas” section contains some information
about the people behind our blog.

Clicking the “share” icon on the upper right corner  of the app will enable you to share the URL of  what you are currently reading in the app.

Clicking the “share” icon on the upper right corner
of the app will enable you to share the URL of
what you are currently reading in the app.

Also, the action overflow will enable you to “refresh” or “copy” the URL of what you are currently reading.

Also, the action overflow will enable you to “refresh” or “copy”
the URL of what you are currently reading.

Now you might ask, what are the functions of those other icons in the navigation drawer?

  1. Like on Facebook – will open the Facebook app with our Facebook page loaded.
  2. Follow on Google+ – will open the Google+ app with our Google+ page.
  3. Follow on Twitter – opens the Twitter app with my twitter account.
  4. Subscribe via email – opens a browser with a feedburner form for email subscription.
  5. Send Feedback – will open the Gmail app pre-loaded with my email, subject and content.

Our app will automatically detect if one of those apps were not installed. It will tell the user “[app_name] does not exist!”

In the future, I want this app to have an offline feature, like the app is able to download useful tutorials or posts on the device so it can be viewed without internet connection.

As of the moment, I only tested this app on my phone and 10.1 tablet (both Jelly Bean). I looks good and works fine for me. You might encounter performance issues, bugs or crashes, the usual things for a beta release. Please don’t hesitate to report them to me, the same if you have any comments or suggestion for our app’s improvement. Thanks!

Thanks for reading this Introducing The Code Of A Ninja’s Android App (Beta)!

Ways to Create a Splash Screen for Android App

Today we’re going to create a splash screen for your Android app. A splash screen is usually an image or a view that appears to the user while the app is loading, it is also a way to make your brand or logo easier to be recognize by the user. Some android apps that uses splash screens include Facebook, Pocket and of course, the game apps. I’m going to show you two ways to create android splash screens.

Example logo to be seen in our splash screen.

Example logo to be seen in our splash screen.

Splash Screen With Two Activities

The first way I’m gonna teach you is using two activities, the first activity will be our splash screen and the second activity will be our app’s main screen. The splash screen activity will be shown for four seconds and then it will show the next activity. Download the code here:

Download Code

Here are the files we need:

Highlighted are the files we have to create.

Highlighted are the files we have to create.

SplashScreenActivity.java – The initial activity executed. This activity will end with an animation that depends on the device.

        // remove title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // our layout xml
        setContentView(R.layout.activity_splash_screen);

        // we're gonna use a timer task to show the main activity after 4 seconds
        TimerTask task = new TimerTask() {

            @Override
            public void run() {

                // go to the main activity
                Intent nextActivity = new Intent(SplashScreenActivity.this,
                        MainActivity.class);
                startActivity(nextActivity);

                // make sure splash screen activity is gone
                SplashScreenActivity.this.finish();

            }

        };

        // Schedule a task for single execution after a specified delay.
        // Show splash screen for 4 seconds
        new Timer().schedule(task, 4000);

    }

}

MainActivity.java – Our app’s main screen, where the main functions of your app should be seen.

package com.example.splashscreenexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // remove title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        // our main activity layout
        setContentView(R.layout.activity_main);
        
    }
}

codeofaninja350pxwidth.png – An example image used in the splash screen. This is included in the code download.

Splash Screen with One Activity

The second way to create a splash screen is using just one activity – your MainActivity. It should be covered with an ImageView first and then after few seconds, it will disappear with a simple fade-out animation to make it look smooth. Download code this code:

Download Code

Files we need are highlighted below:

We’ll work on three files in this example.

We’ll work on three files in this example.

MainActivitity.java – The file with double purpose, it will show our splash screen and then main screen.

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // remove title bar.
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);

        // our timer task.
        TimerTask task = new TimerTask() {

            @Override
            public void run() {

                // we have to run it on UI thread so we won't get view error
                MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {

                        // get the splash image
                        ImageView splashImage = (ImageView) MainActivity.this
                                .findViewById(R.id.imageViewSplashLogo);
                        
                        // make the splash image invisible
                        splashImage.setVisibility(View.GONE);

                        // specify animation
                        Animation animFadeOut = AnimationUtils.loadAnimation(MainActivity.this,
                                R.anim.splash_screen_fadeout);
                        
                        // apply the animattion
                        splashImage.startAnimation(animFadeOut);
                        
                    }
                });

            }

        };

        // Schedule a task for single execution after a specified delay.
        // Show splash screen for 4 seconds
        new Timer().schedule(task, 4000);

    }

}

splash_screen_fadeout.xml – It will make our splash screen gone beautifully – a simple fade-out animation.

<?xml version="1.0" encoding="utf-8"?>
<!--
    -zAdjustment makes sure the activity is on top
    -interpolator defines the rate of change of an animation
    -we use decelerate_interpolator to reduce animation speed from visible (Alpha 1.0) to invisible (Alpha 0.0)
-->
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:toAlpha="0.0"
    android:zAdjustment="top" />

codeofaninja350pxwidth.png – our example logo.

Output screenshots:

Splash screen.

Splash screen.

Main Activity.

Main Activity.

Thanks for reading this Ways to Create a Splash Screen for Android App!

Android Share Intent Example for URL, Text or Image

Today I’m going to give you an android share intent example that you can use to enable your app to share contents such as URL or text and Image to other apps installed in your Android device like Facebook, Twitter, Messaging, Instagram, Evernote, etc.. Example uses of this code include:

You are building an app that browses a certain website or URL.

Your app generates an image that a user can share.

android share intent example

DOWNLOAD CODE

Android Share Intent Example Step by Step

Step 1: Prepare XML Layout, we’ll have activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/buttonShareTextUrl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Share Text or URL" />

    <Button
        android:id="@+id/buttonShareImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/buttonShareTextUrl"
        android:text="Share Image" />

</RelativeLayout>

Step 2: Inside the onCreate method of MainActivity.java, put the buttons and OnClickListener handlers.

// listeners of our two buttons
View.OnClickListener handler = new View.OnClickListener() {
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.buttonShareTextUrl:
			shareTextUrl();
			break;

		case R.id.buttonShareImage:
			shareImage();
			break;
		}
	}
};

// our buttons
findViewById(R.id.buttonShareTextUrl).setOnClickListener(handler);
findViewById(R.id.buttonShareImage).setOnClickListener(handler);

Step 3: As you’ve noticed, we have shareTextUrl() method that will be triggered every time the user clicks on the “Share Text or URL” button.

private void shareTextUrl() {
	Intent share = new Intent(android.content.Intent.ACTION_SEND);
	share.setType("text/plain");
	share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

	// Add data to the intent, the receiving app will decide
	// what to do with it.
	share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");
	share.putExtra(Intent.EXTRA_TEXT, "http://www.codeofaninja.com");

	startActivity(Intent.createChooser(share, "Share link!"));
}

Step 4: We also have shareImage() method for sharing images. It is triggered when the user clicks on the “Share Image” button.

private void shareImage() {
	Intent share = new Intent(Intent.ACTION_SEND);

	// If you want to share a png image only, you can do:
	// setType("image/png"); OR for jpeg: setType("image/jpeg");
	share.setType("image/*");

	// Make sure you put example png image named myImage.png in your
	// directory
	String imagePath = Environment.getExternalStorageDirectory()
			+ "/myImage.png";

	File imageFileToShare = new File(imagePath);

	Uri uri = Uri.fromFile(imageFileToShare);
	share.putExtra(Intent.EXTRA_STREAM, uri);

	startActivity(Intent.createChooser(share, "Share Image!"));
}

Complete MainActivity.java code:

package com.example.androidshareurlintent;

import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.app.Activity;
import android.content.Intent;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // listeners of our two buttons
        View.OnClickListener handler = new View.OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {

                case R.id.buttonShareTextUrl:
                    shareTextUrl();
                    break;

                case R.id.buttonShareImage:
                    shareImage();
                    break;
                }
            }
        };

        // our buttons
        findViewById(R.id.buttonShareTextUrl).setOnClickListener(handler);
        findViewById(R.id.buttonShareImage).setOnClickListener(handler);

    }

    // Method to share either text or URL.
    private void shareTextUrl() {
        Intent share = new Intent(android.content.Intent.ACTION_SEND);
        share.setType("text/plain");
        share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        // Add data to the intent, the receiving app will decide
        // what to do with it.
        share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");
        share.putExtra(Intent.EXTRA_TEXT, "http://www.codeofaninja.com");

        startActivity(Intent.createChooser(share, "Share link!"));
    }

    
    // Method to share any image.
    private void shareImage() {
        Intent share = new Intent(Intent.ACTION_SEND);

        // If you want to share a png image only, you can do:
        // setType("image/png"); OR for jpeg: setType("image/jpeg");
        share.setType("image/*");

        // Make sure you put example png image named myImage.png in your
        // directory
        String imagePath = Environment.getExternalStorageDirectory()
                + "/myImage.png";

        File imageFileToShare = new File(imagePath);

        Uri uri = Uri.fromFile(imageFileToShare);
        share.putExtra(Intent.EXTRA_STREAM, uri);

        startActivity(Intent.createChooser(share, "Share Image!"));
    }

}

Please note that when you use the setType() method, you are enabling Android to filter what apps can share your content. For example, you are sharing a text or URL, the appropriate apps to be shown can be Facebook, Messaging or Email. If you are sharing an image, proper apps can be Instagram, Snapseed or Picasa.

Today’s code output screenshots

android share intent example first run

Main screen.

Android Share Intent - share text or url

Share Text or URL button was touched. Take note of the apps on the list.

android share intent example - User chose to share to Facebook

User chose to share to Facebook

android share image

“Share Image” button was touched. Apps was different on the list.

Android Share Intent - user chose to share with gmail

User chose to share with Gmail. Our image was attached.

Android Share Intent - user chose to share with snapseed

User chose to share to Snapseed.

If you have any suggestions to improve this post, please drop it in the comments section below! I’ll be glad to update this post for further improvement. Thanks for reading our Android Share Intent Example!