Now you can Subscribe using RSS

Submit your Email


Send Email from Android App directly without Intent

Vishal Shrestha
Sending Email from an Android app is not difficult if you want to open up another Email App that handles sending the Email. We can just achieve that by adding an ACTION_SEND intent and we can also set content type and use extras such as EXTRA_EMAIL, EXTRA_CC and more. If we start this intent, all the apps that can handle emails such as Gmail app, default Email app will be shown in a chooser dialog if you haven't chosen a default already. Then your user can easily manage the creation and sending of the email from the third party app. But that's not always the case, some times we are required to send an Email from our own App with a fixed Email address to a specific Email address, for example if we need to send a password recovery link on the click of Forgot Password, recovery link to the user should be sent by email from within our app with our own Email Address. In this post we will learn how we can send Email directly from an Android App without and Intent. So let us begin.

Screenshot of final App of this tutorial

Steps in sending Email from Android App directly without Intent: 


  • We require 3 jar libraries for allowing us to send Emails, download the three libraries (LINK BELOW)
  • We create a JSSEProvider class.
  • We create a MailSender class that handles Authentication for our Email and sends Email directly without intent.
So now that we have the steps laid out, let's dig deeper on how to send Email Directly form our App, here's a sample video of the Email app that we will create:

Step 1
First of all download the 3 files- Activation.jar, Additional.jar, Mail.jar.
These are libraries that allow us to send Email in Java.
Once you've downloaded theses files, put it in the libs folder inside your app directory. If you don't have a libs folder inside your app folder, create one and place these files inside the folder.

Step 2
Now that you've copied the files in libs directory, it's time to include those libraries as dependencies. You'll need to do some changes in the app level Gradle file.  Add the following lines in you dependencies section:

compile files('libs/activation.jar')
compile files('libs/additional.jar')
compile files('libs/mail.jar')

Now you are done with libraries part and are ready to code the Email Sender App.

Step 3
Create a new class called JSSEProvider it should extend Provider class. JSSE provides a framework and an implementation for the SSL and TLS security and also provides some other functionalities like encryption and more. You can learn more about it here. Now add the following code in the class. Import all the required classes:

public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new<Void>() {
            public Void run() {
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                return null;

Step 4
Create a class that extends javax.mail.Authentication. I've called it Gmail Sender because I'll be sending Email from one of my Gmail account. Now add the following code in the class:

 private String mailhost = "";
    private String user;
    private String password;
    private Session session;

    static {
        Security.addProvider(new JSSEProvider());

    public GMailSender(String user, String password) {
        this.user = user;
        this.password = password;

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getDefaultInstance(props, this);

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
            MimeMessage message = new MimeMessage(session);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
            message.setSender(new InternetAddress(sender));
            if (recipients.indexOf(',') > 0)
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        }catch(Exception e){
            Log.d("mylog", "Error in sending: " + e.toString());

    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;

        public ByteArrayDataSource(byte[] data, String type) {
   = data;
            this.type = type;

        public ByteArrayDataSource(byte[] data) {
   = data;

        public void setType(String type) {
            this.type = type;

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
                return type;

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);

        public String getName() {
            return "ByteArrayDataSource";

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");

Now we have all the required this are we are ready to send Email from our app. We will just create one method in our Activity and call it whenever we need to send the Email to the User. This method will contain your Email Address, your password so you can be authenticated and the email address of your recipient. Let's call this methods sendMessage():

private void sendMessage() {
        final ProgressDialog dialog = new ProgressDialog(ActivityMain.this);
        dialog.setTitle("Sending Email");
        dialog.setMessage("Please wait");;
        Thread sender = new Thread(new Runnable() {
            public void run() {
                try {
                    GMailSender sender = new GMailSender("youremail", "yourpassword");
                    sender.sendMail("EmailSender App",
                            "This is the message body",
                            "your recipient's email");
                } catch (Exception e) {
                    Log.e("mylog", "Error: " + e.getMessage());

Finally we have our app ready and we can call this method whenever we need to send the Email directly from the app without any intents. You can find the full source code below, Cheers!

NOTE: Gmail has disabled logging in to accounts by third party apps. You need to disable this feature of Gmail and allow logging in from any app otherwise you won't be able to login and Emails won't be sent from your account.

Full source code for Email Sender App: Download Email Sender.


Take screenshot and share to facebook using Unity for Android

Vishal Shrestha
In this post we will share the screenshot that we took using Unity's Application.CaptureScreenshot() Method 1. If you haven't check it out here's the post: Take Screenshot and Display using Unity.

In part 1 we took the screenshot using Unity and saved it in the local storage of the device. Now we will get that screenshot and send it to all the available apps like Facebook, Twitter, Instagram in your Android phone. Let's start the screenshot sharing process.

Share screenshot image of Hill Climb

Share screenshot to Social Media - Android Game

First of all we will start sharing once a share button is pressed. We are assuming you have a share button. Here it the function that will be called when you click on the share button. The isProcessing variable is a bool and it check if user has already pressed the share button and the screenshot is being shared now, if not then starts to share the screenshot. The startCoroutine(ShareScreenshot()) is the method doing all the work. StartCoroutine executes the method provided as parameter is a different thread. ShareScreenshot() function has the code to share the screenshot in Android.

On Share Button Press
  public void ShareBtnPress()
        if (!isProcessing)

Now, this is the main part. Here we have used AndroidJavaClass and AndroidJavaObject that can be initialized with the name of the class in Android along with its package. Check out the code below:

IEnumerator ShareScreenshot()

          isProcessing = true;

        string destination = Path.Combine(Application.persistentDataPath, "screenshotroadies.png");

        if (!Application.isEditor)
            AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");
            AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent");
            intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND"));
            AndroidJavaClass uriClass = new AndroidJavaClass("");
            AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("parse", "file://" + destination);
            intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"),
            intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"),
                "Can you beat my score?");
            intentObject.Call<AndroidJavaObject>("setType", "image/jpeg");
            AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
            AndroidJavaObject chooser = intentClass.CallStatic<AndroidJavaObject>("createChooser",
                intentObject, "Share your new score");
            currentActivity.Call("startActivity", chooser);

        isProcessing = false;

The above code creates an intent with the send action and puts the screenshot as an extra. If you are familiar with Intents in Android  this is probably simple for you to understand just by looking at the code.What we are doing is just initialize an Intent. Setting its action to ACTION_SEND. Creating a Uri object with the path of the screenshot to be shared. Passing the URI object as an Stream extra to the intent and then setting "Can you beat my score?" as a string extra and finally setting the type to image/jpeg. Then we are creating a chooser, this pops up all the available applications that can handle this intent. And we are done, now you have your share screenshot functionality complete in your Android Game. If you have any problem feel free to ask in the comments below. Happy Coding!


How to take screenshot and display in game using Unity for Android

Vishal Shrestha
In this post we will learn how to take screenshot of the game in Unity after the player has died or at any time during the game according to user input. Most of the games these days are doing it and people can see the screenshots in the game and get the option to share the screenshot to social media like Facebook, Twitter and more. Today we will discuss the most simple way to take screenshots of the game in Unity and display it on the screen.

If you are interested in sharing the screenshot to Social Media, here's part 2: Share Screenshot.

Here is how Hill Climb Racing uses screenshot.


Take screenshot of game using Unity

We will use the method CaptureScreenshot to take the screenshot. Taking screenshot using this way is very easy but the difficult part is making sure the screenshot has been saved before you display it. If you directly display the screenshot after the CaptureScreenshot method, it's highly likely that the screenshot hasn't been saved yet so you won't have a screenshot to display. The easiest way I've found is using yield. Let's take a look at the code below:

private IEnumerator takeScreenshot(){
        Application.CaptureScreenshot("screenshotmygame.png", 0);
        //So that the screenshot is taken
        yield return new WaitForEndOfFrame ();
        yield return new WaitForSecondsRealtime(1.5f);

StartCoroutine (takeScreenshot ()); 

In the code above we have created a method called takeScreenshot that takes a screenshot using the first line. The first parameter is the name as which the screenshot image will be saved and the second parameter is the factor by which to increase the resolution. I've noticed that keeping the resolution factor just 0 or 1 is find as most of the devices now are already high resolution and the greater the scale the longer it takes to save the screenshot. The screenshots taken at 0 or 1 are just fine for sharing to social media.
In the yield statements that follow the CaptureScreenshot, the first statement waits for the current frame to end before running the next statement. This is supposed to work and the screenshot should be saved by the time frame has ended but that's not always the case, hence the WaitForSecondsRealime Method. The parameter of this method defines for delay after which the following statements should be executed. I've set it to 1.5f, it should be fine for most devices and worked will all the devices I tested. 1.5 seconds should be ample time for the screenshot to save.
The StartCoroutine methods just starts an IEnumerator Method as a Coroutine, i.e the methods is executed in parallel.
Now that we have successfully saved our screenshot, let's take a look at how to get it and display it in the game display.

Display the screenshot

Displaying the screenshot  is also fairly easy. We just need to provide the path of the screenshot, read the file, load it into a texture and override the sprite of Image component. Let's take a look at the code below.
NOTE: Please note that using this approach there is an UI Image component already in the game that set to unactive. It need to be set active before overriding its sprite. In the code below it's finalScreenShot.

public void GetPhoto()
        string url = Application.persistentDataPath + "/"+ "screenshotmygame.png";
        var bytes = File.ReadAllBytes(url);
        Texture2D texture = new Texture2D (2, 2);
        bool imageLoadSuccess = texture.LoadImage(bytes);
        while (!imageLoadSuccess) {
            print ("image load failed");
            bytes = File.ReadAllBytes(url);
            imageLoadSuccess = texture.LoadImage (bytes);
        print ("Image load success: " + imageLoadSuccess);
        finalScreenShot.GetComponent<Image> ().overrideSprite = Sprite.Create (texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0f, 0f), 100f);

We have created a method call GetPhoto() that can be called for displaying the screenshot. the first method is just creating a url for the screenshot to be accessed. We are concatenating the path for game's file with the image name that we created in the first step. Then we real the image file byte by byte. Then we are loading the bytes in a texture. If the loading is failed we try it until it's successful and finally when the image is loaded successfully we just create a sprite from the texture and set it as the sprite of our UI image component. That's it! We have successfully captured the screenshot and then displayed it in our game. Try it out and if you have any questions feel free to comment below. Happy coding! :)
In the next part we will discuss how to share this screenshot to social media.


Responsive column using bootstrap grid system and multiple column types.

Milan Malla
Responsiveness is a must quality for any website these days. And all the beginner web developers know that what a chaotic process it is to obtain a desired result.
Bootstrap has been the savior for a long time for developers like us. The most important aspect of Bootstrap is its 12-column mobile first grid system. This is what you use to create a responsive layout using grids.

For better understanding of 12-column mobile first grid system have look at below table from the official Bootstrap website.

Using bootstrap, you can specify different number of column grids based on different screen sizes.

In this tutorial, you will learn to make columns responsive using more than just one column class prefixes to achieve different number of column grids on different screen sizes.

First of all, you need to download the bootstrap from given link:

Now if we want 4 columns for devices with medium screen size, we would use .col-md-4 and it would give us exactly what we asked for:

<div class="row">
             <div class="col-md-4">
                 <img src="images/guy.jpg" alt="box">
             <div class="col-md-4">
                 <img src="images/guy.jpg" alt="box">
             <div class="col-md-4">
                 <img src="images/guy.jpg" alt="box">
             <div class="col-md-4">
                 <img src="images/guy.jpg" alt="box">


Works well in devices having medium screen size, but in large devices the columns would look big and in small devices too small.

What most of the beginners don't know is that we can integrate more than one column types to    achieve optimized solution.

Lets say we want 4 columns for large devices, 3 columns for medium devices, 2 columns for small devices (tabloids) and 1 column for mobile devices.

What we do is write this simple piece of code:

<div class="row">
             <div class="col-lg-3 col-md-4 col-sm-6">
                 <img src="images/guy.jpg" alt="box">
             <div class="col-lg-3 col-md-4 col-sm-6">
                 <img src="images/guy.jpg" alt="box">
             <div class="col-lg-3 col-md-4 col-sm-6">
                 <img src="images/guy.jpg" alt="box">
             <div class="col-lg-3 col-md-4 col-sm-6">
                 <img src="images/guy.jpg" alt="box">

With above piece of code we get what we desired in best possible way. What we have done is defined class prefixes for different screen sizes. In the code above, class prefix col-lg-3 assigns 3 of the 12 available grids to one column, meaning there will be 4 columns in large devices, similarly col-md-4 means 3 columns in devices with medium screen size as 4 * 3 equals 12 and col-sm-6 means 2 columns will be displayed in devices with small screen size and 6*2 equals 12. Pretty neat right?
So, that is all for this tutorial. We will learn more about Bootstrap, columns, layouts and more designing techniques in upcoming tutorial. If you have any problems or comments feel free to comment below. Happy Coding.


How to get full sized Image from Camera Android

Vishal Shrestha
Getting Image from Camera in Android is pretty simple, however it gets pretty tricky if you need to get full quality image from the camera. When you launch intent with action image capture and only use the data.getExtras().get("data"), what you basically get is just the thumbnail. For getting the high quality full size photo, you need to save the high quality photo in the phone storage or external storage and then get that photo using Uri. Without saving the photo, you cannot get a high quality photo from the camera. Luckily it's not that complex also, here are the steps involved in getting full sized picture from the camera in Android.


Get full sized image from camera in Android.

  1.  Create FileProvider: Most important thing to get a full sized image is to use a file provide. It is using file provider that you access the file that has been stored after been taken from the camera. To create fileProvider, write the following code in Manifest.xml:
  2. Create file path in xml: Now you need to create a file in xml that defines path where images will be stored. Create a new folder in res called xml and create a new file called file_paths.xml inside it and add the following code:

    <?xml version="1.0" encoding="utf-8"?>
        <external-path name="my_images" fullpath="storage/emulated/0/Pictures/" />
  3. Get file write permission: As I've already mentioned you'll need to save the high quality full resolution first, before you can use it. So you need to the file write permissions so that you can save the photo first. Define this in manifest first - 

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

    Now if you plan on using the app on devices greater then Marshmallow, which you probably should right now you will need  to ask for permission on runtime. Here's how you do it-

    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

    Now you can handle whether the user has selected give permission of not in onRequestPermissionsResult. Once you have the permission, create an Image_capture intent.
  4. Create Image capture intent: Now create a new intent with image capture action. Here's the code:
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  5. Create a file and get file path and Start the action image capture intent:Now you need to create file, this is the file in which the image will be saved. Once the file is created get the path of the file.

       File photoFile = null;
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.d("mylog", "Exception while creating file: " + ex.toString());
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    Log.d("mylog", "Photofile not null");
                    Uri photoURI = FileProvider.getUriForFile(ActivityMain.this,
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

    Here's the code for createImageFile()

    private File createImageFile() throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File image = File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */

            // Save a file: path for use with ACTION_VIEW intents
            mCurrentPhotoPath = image.getAbsolutePath();
            Log.d("mylog", "Path: " + mCurrentPhotoPath);
            return image;
  6. Handle the intent response in onActivityResult(){}. Now you've got everything in place, now just get the full size image from the storage and display in an imageView or upload it or do anything you want with it. Here how you get the full size image from storage after it's been captured.
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            } else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
                Uri uri = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                } catch (IOException e) {
You are done, now you should be able to successfully get full sized image from your phone's camera. If you have any problem, feel free to comment below. Happy coding!


Rounded corners in ImageView Android Tutorial/Example

Vishal Shrestha
To get full sized from the android camera, you need to use file provider as shown in example below. What generally happens when using camera to get photos is you only get the thumbnail quality image from the data.getExtras, so to get full size image you need to save it in phone storage first and then use that image. Here are the steps involved in getting full sized image... As it's clear from the title already, in this post we will discuss how we can display round corners in an ImageView. There can be several ways to show rounded corners, some of the ones I have tried are:
  • Using a library like this one: Rounded ImageView Library
  • Create a CardView with required corner radius and put ImageView inside it.
  • Add rounding to the image itself.
In this post we will do everything our-self because, a: It's ease and b: We can. ;)
So let get started:

Here's the screenshot of rounded corner effect we will create as a result of this example:

Round Corner in ImageView

How to Round the corners of an Image

Let's first understand how we will be rounding the corners the Image. It just requires two steps
  1. First we will draw a rectangle on a canvas with the required roundness of corners.
  2. Then we will draw the required Bitmap on the canvas with the PorterDuff.Mode.SRC_IN mode set in the paint. You are probably confused about PorterDuff, I was too. It's basically a way to merge different images with each other where different images are on different layers similar to Photoshop. Below is the image of different PorterDuff modes. You can read more about it here: PorterDuff Modes:
  3. Porter-Duff-Mode-used-for-rounding-corners-in-imageView
    Porter Duff Modes
  4. You are done! Just return the new Bitmap created by step 1 and 2 and display it in ImageView.
The Code for Rounding the corners of Image.

1. activity_main.xml
This is simple we just two ImageViews where we will add images after the corner of the image has been rounded.

<LinearLayout xmlns:android=""

        android:layout_height="246dp" />

        android:layout_height="246dp" />


This is the meat of the code.  The getRoundedCornerBitmap method takes the Bitmap and the required rounded of corners as parameter and returns new Bitmap with round corners. I've comment all the main parts of the code should be self explanatory.

package com.vysh.corneredimage;


public class ImageConverter {
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {

        //Setting the width and height of the Bitmap that will be returned                        //equal to the original Bitmap that needs round corners.
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

        //Creating canvas with output Bitmap for drawing
        Canvas canvas = new Canvas(output);

        //Setting paint and rectangles.
        final int color = Color.BLACK;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        //SetXfermode applies PorterDuffXfermode to paint.
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;

We have everything ready, now we just need the use our ImageConverter class's getRoundedCornerBitmap Method and apply the returned Bitmap as ImageView's background and we are done!

package com.vysh.corneredimage;

import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    ImageView iv1, iv2;
    protected void onCreate(Bundle savedInstanceState) {

        iv1 = (ImageView)findViewById(;
        iv2 = (ImageView)findViewById(;

        Bitmap bitmap1 = BitmapFactory.decodeResource(this.getResources(),R.drawable.img1);
        Bitmap circularBitmap1 = ImageConverter.getRoundedCornerBitmap(bitmap1, 100);
        Bitmap bitmap2 = BitmapFactory.decodeResource(this.getResources(),R.drawable.img2);
        Bitmap circularBitmap2 = ImageConverter.getRoundedCornerBitmap(bitmap2, 100);



Voila! now you have finally created Images with round corner. If you have any questions, feel free to comment below. Happy Coding.

Source code: Rounded Corners in ImageView Example


Complete Braintree Integration in Android Tutorial.

Vishal Shrestha
In this post we will completely integrate Braintree payment in an Android app. We will also create our own PHP server side scripts to fully understand the functioning. If you are not familiar with PHP you don't need to worry, we will just create two PHP methods and it's fairly simple, you will understand it in no time. You can download the full source code at the bottom of this post.
Let's first discuss how Braintree Payments in an App works. There are two parts to it:
1. The Client Side (Android App)
2. The Server Side.

Let's first discuss the client side, the client side includes the following steps:

Client Side for Braintree Integration. (Pic Courtesy: Braintree)
  1. Our app requests the token from Server. 
  2. The server generates a token using Braintree's SDK and sends it back to the android app). 
  3. The app then gets the user's credit card info and then contacts the Braintree server to receive a payment nonce.
  4. After the app receives the payment nonce from the Braintree server, it will contact our own server with payment amount and Nonce. (The server then handles payment and has to send information to the app whether the payment was successful of not)
Now in the server side, we do the following tasks:
Braintree integration in Android app server side (Pic courtesy: Braintree)

  1. The server receives token request from the client (Our Android app).
  2. Server generates the token and sends back the token to app.
  3. (Step 4 in image above)The server receives the payment details and nonce from the client app.
  4. (Step 5 in image above)Our server contacts the Braintree server with Nonce and get response if the payment was successful or not.
Now that we have understood how the payment process works, let's start with some actual coding, first let's do the client side.

Steps to Integrate Braintree Payment in Android App (Client Side). 

First of all, let's add dependencies for using Braintree. We will also add dependency for using Volley using which we will create API requests. Add the dependencies in app level Gradle file as shown below. Dependencies are :

          compile 'com.braintreepayments.api:drop-in:3.+
     compile ''


Now let's create layout for the app, we have a simple layout with an EditText where the user will enter the amount to pay and a button to make the payment.


Here's the code for the layout main_activity.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""


            android:text="Ready for transaction"
            android:textStyle="bold" />


                android:hint="Choose the amount to pay" />


            android:textColor="@android:color/white" />


Notice that we've added visibility:gone in our nested linear layout as we first want to get the token from server, only then we want to show form to user to make payments as we need token for payments and we cannot make payments through Braintree without tokens. Once we get the token, we set its visibility to visible.

Now we will create the Here's the code for it:
Note: As we have not created APIs yet for getting token, we will leave that variable empty for now. After we create APIs we will add our API.
Steps in this Activity:
  1. We first call our API that will get the client token using an Async class(API is created at the end of this post).
  2. Once we've successfully got the client token, we can use that to make payments using Braintree. So we set the visibility of the form to Visibile so that user can enter the amount to pay.
  3. Once user click's the pay button, we present user a DropInForm. DropInForm is Braintree's default form where user need to enter their credit card details. It's Braintree's default implementation to get user card data. Once the user enters his/her details, the details are directly sent to Braintree's server and the server returns a Nonce to the app.
  4. Once the Nonce is received from the Braintree server, we send the Nonce along with the amount that user has entered in the 2nd step to our own server using an API that we'll create in the end of this post.
  5. Finally we receive reply from our server regarding the payment.

public class MainActivity extends AppCompatActivity {

    final int REQUEST_CODE = 1;
    final String get_token = "YOUR-API-TO-GET-TOKEN";
    final String send_payment_details = "YOUR-API-FOR-PAYMENTS";
    String token, amount;
    HashMap<String, String> paramHash;

    Button btnPay;
    EditText etAmount;
    LinearLayout llHolder;

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        llHolder = (LinearLayout) findViewById(;
        etAmount = (EditText) findViewById(;
        btnPay = (Button) findViewById(;
        btnPay.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
        new HttpRequest().execute();

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                DropInResult result = data.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT);
                PaymentMethodNonce nonce = result.getPaymentMethodNonce();
                String stringNonce = nonce.getNonce();
                Log.d("mylog", "Result: " + stringNonce);
                // Send payment price with the nonce
                // use the result to update your UI and send the payment method nonce to your server
                if (!etAmount.getText().toString().isEmpty()) {
                    amount = etAmount.getText().toString();
                    paramHash = new HashMap<>();
                    paramHash.put("amount", amount);
                    paramHash.put("nonce", stringNonce);
                } else
                    Toast.makeText(MainActivity.this, "Please enter a valid amount.", Toast.LENGTH_SHORT).show();

            } else if (resultCode == Activity.RESULT_CANCELED) {
                // the user canceled
                Log.d("mylog", "user canceled");
            } else {
                // handle errors here, an exception may be available in
                Exception error = (Exception) data.getSerializableExtra(DropInActivity.EXTRA_ERROR);
                Log.d("mylog", "Error : " + error.toString());

    public void onBraintreeSubmit() {
        DropInRequest dropInRequest = new DropInRequest()
        startActivityForResult(dropInRequest.getIntent(this), REQUEST_CODE);

    private void sendPaymentDetails() {
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, send_payment_details,
                new Response.Listener<String>() {
                    public void onResponse(String response) {
                            Toast.makeText(MainActivity.this, "Transaction successful", Toast.LENGTH_LONG).show();
                        else Toast.makeText(MainActivity.this, "Transaction failed", Toast.LENGTH_LONG).show();
                        Log.d("mylog", "Final Response: " + response.toString());
                }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                Log.d("mylog", "Volley error : " + error.toString());
        }) {
            protected Map<String, String> getParams() {
                if (paramHash == null)
                    return null;
                Map<String, String> params = new HashMap<>();
                for (String key : paramHash.keySet()) {
                    params.put(key, paramHash.get(key));
                    Log.d("mylog", "Key : " + key + " Value : " + paramHash.get(key));

                return params;

            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                return params;

    private class HttpRequest extends AsyncTask {
        ProgressDialog progress;

        protected void onPreExecute() {
            progress = new ProgressDialog(MainActivity.this,;
            progress.setMessage("We are contacting our servers for token, Please wait");
            progress.setTitle("Getting token");

        protected Object doInBackground(Object[] objects) {
            HttpClient client = new HttpClient();
            client.get(get_token, new HttpResponseCallback() {
                public void success(String responseBody) {
                    Log.d("mylog", responseBody);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(MainActivity.this, "Successfully got token", Toast.LENGTH_SHORT).show();
                    token = responseBody;

                public void failure(Exception exception) {
                    final Exception ex = exception;
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(MainActivity.this, "Failed to get token: " + ex.toString(), Toast.LENGTH_LONG).show();
            return null;

        protected void onPostExecute(Object o) {

Steps to Integrate Braintree Payment in Android App (Server Side - PHP). 

Getting Braintree API Key Credentials:

To get started with back-end first we need to create a Braintree account. Go to Braintree and create a new account if you don't have one already, then login to the Braintree control panel. Then hover over account on top navigation bar and click on my user. You will see a page similar to this. Then click on view right next to the public key.


Once you clicked on view you will see a page similar to this, select PHP as the language above the details that are provided. You will need these details in the next step.


Server Side coding in PHP: 

Steps involved in server side development:
Note: I've used  XAMPP for server side functionality. The following will assume you have installed XAMPP.
  1. Download Braintree's PHP SDK, I do it using composer.
  2. Create API for sending token.
  3. Create API for receiving payment details and sending Braintree server's reply.
Let's use composer for downloading Braintree's PHP SDK. Download composer from here: Composer.
After downloading, install composer. Create a folder inside C:\xampp\htdocs. I've named it BraintreePayments. Now create a composer.json file in your root directory (BraintreePayments). Copy this inside the file.

  "require" : {
    "braintree/braintree_php" : "3.23.0"

Once you copied and saved the code above inside composer.json, Open the terminal in your root directory(Directory with composer.json) and execute composer install. It will download Braintree's PHP SDK and you will finally be ready to code API for you Andoird App. Once everything is finished. Create a new folder inside BraintreePayments, name it include and create a new file braintree_init.php inside it. Copy the following code in it, these are just your API credentials that you will need:

if(file_exists(__DIR__ . "/../.env")) {
    $dotenv = new Dotenv\Dotenv(__DIR__ . "/../");
Check the step above this one to check how to get you API credentials. Once your saved this file, go back to the root directory. Create a new file, call it main.php and write the following code in it:

require_once ("include/braintree_init.php");
require_once 'vendor/braintree/braintree_php/lib/Braintree.php';
echo ($clientToken = Braintree_ClientToken::generate());

This code simply echos (Displays) the clientToken, but when we call this file from our Android Device we will receive this token and we can use it further for contacting Braintree's server.

After main.php is ready, create a new file name it checkout.php. This file will deal with getting payment amount and Nonce from the client and sending it to the Braintree server. It will receive the reply from Braintree server and we can take steps accordingly.  In this example, we don't parse the reply from server. We will straight away send the response to our App and if it contains the text successful, we will toast payments was successful, or else, payment failed.
Here's the code for checkout.php:
require_once ("include/braintree_init.php");
require_once 'vendor/braintree/braintree_php/lib/Braintree.php';

$nonce = $_POST['nonce'];
$amount = $_POST['amount'];
$result = Braintree_Transaction::sale([
  'amount' => $amount,
  'paymentMethodNonce' => $nonce,
  'options' => [
    'submitForSettlement' => True
echo $result;

Finally we are ready, we have created the app and we have also done the server side coding. But to use test this app we need to do one more thing, Start XAMPP and find out you ip address(Type ipconfig in terminal) and set the get_token variable that we created in the to http://YOURIP/YOUR-ROOT-FOLDER/main.php and set send_payment_details variable to http://YOURIP/YOUR-ROOT-FOLDER/checkout.php. Bravo, we done it. Now build and test you app!

Download full Android app with Braintree Integration: BraintreePayments
Server Side Code: BraintreePaymentsServer.
In case you are wondering what the Braintree's server replies to our server, here's what it looks like, in actual production this needs to be properly parsed by the server, but we are just sending it to our Android app and if it contains the word successful, we show a toast message as Payment successful.


Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha