Wednesday, March 27, 2013

Http authentication ajax jquery

Http authentication ajax jquery

     Http authentication through ajax jQuery.          
  1. Force HTTPS for authentication.
  2. Allow testing HTTPS without installing a certificate locally.
  3. Implement a RESTful LoginService that allows users to login.
  4. Implement login with Ajax, with the request coming from an insecure page.
                          $
.ajax({
                          type : 'POST',
url : 'Enter your url',
data : data,
dataType : 'json',
                                        beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "Basic "
+ base64.encode("username:password"));
},
success : function(response) {
},
error : function(jqXHR, exception) {
                                        }
                          });



Make a new file named as base64.js
var base64 = {};
(function() {
var END_OF_INPUT = -1, base64Chars = new Array('A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '+', '/'), reverseBase64Chars = new Array(), base64Str, base64Count;

for ( var i = 0; i < base64Chars.length; i++) {
reverseBase64Chars[base64Chars[i]] = i;
}

function setBase64Str(str) {
base64Str = str;
base64Count = 0;
}
function readBase64() {
if (!base64Str)
return END_OF_INPUT;
if (base64Count >= base64Str.length)
return END_OF_INPUT;
var c = base64Str.charCodeAt(base64Count) & 0xff;
base64Count++;
return c;
}
function readReverseBase64() {
if (!base64Str)
return END_OF_INPUT;
while (true) {
if (base64Count >= base64Str.length)
return END_OF_INPUT;
var nextCharacter = base64Str.charAt(base64Count);
base64Count++;
if (reverseBase64Chars[nextCharacter]) {
return reverseBase64Chars[nextCharacter];
}
if (nextCharacter == 'A')
return 0;
}
return END_OF_INPUT;
}

function ntos(n) {
n = n.toString(16);
if (n.length == 1)
n = "0" + n;
n = "%" + n;
return unescape(n);
}

base64.encode = function(str) {
setBase64Str(str);
var result = '';
var inBuffer = new Array(3);
var lineCount = 0;
var done = false;
while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT) {
inBuffer[1] = readBase64();
inBuffer[2] = readBase64();
result += (base64Chars[inBuffer[0] >> 2]);
if (inBuffer[1] != END_OF_INPUT) {
result += (base64Chars[((inBuffer[0] << 4) & 0x30)
| (inBuffer[1] >> 4)]);
if (inBuffer[2] != END_OF_INPUT) {
result += (base64Chars[((inBuffer[1] << 2) & 0x3c)
| (inBuffer[2] >> 6)]);
result += (base64Chars[inBuffer[2] & 0x3F]);
} else {
result += (base64Chars[((inBuffer[1] << 2) & 0x3c)]);
result += ('=');
done = true;
}
} else {
result += (base64Chars[((inBuffer[0] << 4) & 0x30)]);
result += ('=');
result += ('=');
done = true;
}
lineCount += 4;
if (lineCount >= 76) {
result += ('\n');
lineCount = 0;
}
}
return result;
}

base64.decode = function(str) {
setBase64Str(str);
var result = "";
var inBuffer = new Array(4);
var done = false;
while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
&& (inBuffer[1] = readReverseBase64()) != END_OF_INPUT) {
inBuffer[2] = readReverseBase64();
inBuffer[3] = readReverseBase64();
result += ntos((((inBuffer[0] << 2) & 0xff) | inBuffer[1] >> 4));
if (inBuffer[2] != END_OF_INPUT) {
result += ntos((((inBuffer[1] << 4) & 0xff) | inBuffer[2] >> 2));
if (inBuffer[3] != END_OF_INPUT) {
result += ntos((((inBuffer[2] << 6) & 0xff) | inBuffer[3]));
} else {
done = true;
}
} else {
done = true;
}
}
return result;
}
})()



Wednesday, March 13, 2013

Setup android, java and Eclipse on your system

 Downloading and Installation of Java Development Kit( JDK)

  1. Go to Java SE download and download jdk1.6.0.
  2. Double-click on the install file and it should open an installer.
  3. Click next, then read and accept the license.
  4. On the next screen you will encounter some options. Just leave these alone and click next unless you know what you are doing.
  5. The next page you encounter should install (and in some cases download) the Java Development Kit.
  6. After the installer is finished, open run by clicking Start --> Run.
  7. In the text box, type "cmd" and click "OK".
  8. A simple window should be opened with a black background and a text prompt.
  9.  After focusing the window, type "javac" and press enter. If the prompt returns something along the lines of: ''javac'' is not recognized as an internal or external command, operable program or batch file" then continue with the next step. If it shows many more options and lines, skip the all next steps of JDK installation.
  10. Open the properties of "My Computer" by either right-clicking the icon on the desktop or right-clicking Start --> My Computer. When the pop up menu opens, scroll to the bottom and select "Properties".
  11. Open a window then click on "Advanced System Setting".
  12. This should open a window named "System Properties". Click on the "Advanced" tab and then click "Environment Variables".
  13. Next, another window opens now select the "Path" variable in the system variables.
  14. Now click on edit button. It opens a new window named "Edit System Variable".
  15. Now Careful not to delete anything in variable value text box. At the end of the text box, add a semi-colon if there is not one already, and add "C:\Program Files\Java\jdk1.6.0\bin" to the text box. This is assuming you did not change the file path of the installation.
  16. Click "Apply" and "OK" to all the windows you have just opened. Open the command prompt again, while following steps 6-9 to see if that "javac" command works.

Download Android SDK

  1. Download and install Java Development Kit(JDK) if not installed already.
  2. Go to this link.
  3. Select the Android Software Development Kit (SDK)  for windows make sure to choose the version that is correct for your operating system.
  4. After your Android SDK download is complete, unzip and move this folder to a permanent location.

Install Eclipse IDE follow these steps:

  1. Go to this link.
  2. Select the Eclipse classic 4.2.2                                                                                                                                           For Windows users, you will have to know what type of version of your OS you have. If your computer is a 64 bit Windows, select Windows 64 and if you have a 32 bit Windows, select Windows 32 bit.
  3. Once you have downloaded the Eclipse archive you will need to decompress the zip file, which will create the unzipped Eclipse folder. You may want to extract the archive to the root of C:\ drive, thus creating the folder “C:\eclipse”, or just moved the extracted eclipse folder to the root of C:\ drive if you extracted it already. Since Eclipse does not have any installer, there will be a file inside the Eclipse folder named eclipse.exe ( ). You can double click on the file to run Eclipse.
  4. After eclipse has been fully installed and extracted, create a workspace folder where you will contain all the program files you create.
  5. Now that you have finished installing eclipse restart your computer. By restarting your computer it refreshes system memory and allows changes made by installers and uninstallers to take effect.

Installing the Eclipse Plugin for Android :

  1. Start Eclipse, then select Help > Install New Software. 
  2. Click Add, in the top-right corner.
  3. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location.
  4. Click OK.                                                                                                                                                                         If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).
  5. In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
  6. In the next window, you'll see a list of the tools to be downloaded. Click Next.
  7. Read and accept the license agreements, then click Finish.If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.
  8. When the installation completes, restart Eclipse.

Configuring Android SDK:

1.      After you’ve successfully downloaded the ADT as described above, the next step is to modify your ADT preferences in Eclipse to point to the Android SDK directory: Select Window --> Preferences to open the Preferences panel.
2.       Select Android from the left panel.You may see a dialog asking whether you want to send usage statistics to Google. If so, make your choice and click Proceed. You cannot continue with this procedure until you click Proceed.
3.       For the SDK Location in the main panel, click Browse and locate your downloaded SDK directory.
Click Apply, then OK.
       Run Application on Run on the Emulator:

To run your app on the emulator you need to first create an Android Virtual Device (AVD). An AVD is a device configuration for the Android emulator that allows you to model different devices.

Create an AVD:

1. Launch the Android Virtual Device Manager : In Eclipse, click Android Virtual Device Manager icon from the toolbar.
  1. In the Android Virtual Device Manager panel, click New.
  2. Fill in the details for the AVD. Give it a name, a platform target, an SD card size, and a skin (HVGA is default).
  3. Click Create AVD.
  4. Select the new AVD from the Android Virtual Device Manager and click Start.
After the emulator boots up, unlock the emulator screen.

Import the Existing project into Eclipse:
  1. From the main menu bar, select File --> Import Then Import wizard opens.
  2. Select Android > Existing Android Code into Workspace and click Next.
  3. Choose either Select root directory or Select archive file and click the associated Browse to locate the directory or file containing the project.
  4. Under Projects select the project.
  5. Click Finish to start the import.
  6. After that the project folder is appear in the Package Explorer.

Sunday, March 10, 2013

SMSplugin Phonegap android

Follows these steps:

1. Include the smsplugin.js to your project within asset/www/ folder and include a reference to it in your html files.
Copy and paste below the js code to your smsplugin.js file.
var SmsPlugin = function() {};
var sendSMS = {
send : function(phone, message, successCallback, failureCallback) {
return cordova.exec(successCallback, failureCallback, ‘SmsPlugin’,
“SendSMS”, [ phone, message ]);
}
};
if (!window.Cordova) {
window.Cordova = cordova;
};
if (!window.plugins)
window.plugins = {};
window.plugins.SmsPlugin = new SmsPlugin();
2. Add the sms java file to your scr to your project’s hierarchy.
   Copy and paste below the code to your sms java file.
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class SmsPlugin extends Plugin {
public final String ACTION_SEND_SMS = “SendSMS”;
public int mToastTime = 300000;
public static PluginResult result;
@Override
public PluginResult execute(String action, JSONArray arg1, String callbackId) {
result = new PluginResult(Status.INVALID_ACTION);
String phoneNumber = null;
String message = null;
try {
phoneNumber = arg1.getString(0);
message = arg1.getString(1);
} catch (JSONException e) {
e.printStackTrace();
}
if (phoneNumber.length() > 0 && message.length() > 0) {
if (action.equals(ACTION_SEND_SMS)) {
TelephonyManager telMgr = (TelephonyManager) cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
int simState = telMgr.getSimState();
switch (simState) {
case TelephonyManager.SIM_STATE_ABSENT:
Toast.makeText(cordova.getActivity(), “No Sim Card found”, mToastTime).show();
break;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
Toast.makeText(cordova.getActivity(), “SIM_STATE_NETWORK_LOCKED”, mToastTime).show();
break;
case TelephonyManager.SIM_STATE_PIN_REQUIRED:
Toast.makeText(cordova.getActivity(), “SIM_STATE_PIN_REQUIRED”, mToastTime).show();
break;
case TelephonyManager.SIM_STATE_PUK_REQUIRED:
Toast.makeText(cordova.getActivity(), “SIM_STATE_PUK_REQUIRED”, mToastTime).show();
break;
case TelephonyManager.SIM_STATE_READY:
sendSMS(phoneNumber, message); // method to send message
break;
case TelephonyManager.SIM_STATE_UNKNOWN:
Toast.makeText(cordova.getActivity(), “SIM_STATE_UNKNOWN”, mToastTime).show();
break;
}
}
} else
Toast.makeText(cordova.getActivity(), “Please enter both phone number and message.”, mToastTime).show();
return stopTimer(result);
}

private void sendSMS(String phoneNumber, String message) {
String SENT = “SMS_SENT”;
String DELIVERED = “SMS_DELIVERED”;
PendingIntent sentPI = PendingIntent.getBroadcast(cordova.getActivity(), 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(cordova.getActivity(), 0, new Intent(DELIVERED), 0);
// —when the SMS has been sent—final String string =
cordova.getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(cordova.getActivity(), “SMS sent”, mToastTime).show();
result = new PluginResult(Status.OK);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(cordova.getActivity(), “Generic failure”, mToastTime).show();
result = new PluginResult(Status.ERROR);
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(cordova.getActivity(), “No service”, mToastTime).show();
result = new PluginResult(Status.ERROR);
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(cordova.getActivity(), “Null PDU”, mToastTime).show();
result = new PluginResult(Status.ERROR);
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(cordova.getActivity(), “Radio off”, mToastTime).show();
result = new PluginResult(Status.ERROR);
break;
}
}
}, new IntentFilter(SENT));
// —when the SMS has been delivered—
cordova.getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(cordova.getActivity(), “SMS delivered”, mToastTime).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(cordova.getActivity(), “SMS not delivered”, mToastTime).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
public static PluginResult stopTimer(PluginResult st) {
Thread mSplashThread = new Thread() {
public void run() {
try {
synchronized (this) {
wait(5000);
}
} catch (InterruptedException ex) {
}
}
};
mSplashThread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}
}
3. Add the refrence plugin in you res/plugin.xml file.
<plugin name=”SmsPlugin”  value=”com.example.phonegapapp.SmsPlugin” />
4. Add the sms permission in manifest file.
<uses-permission android:name=”android.permission.SEND_SMS” /> 
5. Call the following function in java script file to send the sms.
sendSMS.send(‘Mobile Number’, ‘Text’, ‘Call back function on complete’);

Saturday, February 16, 2013

Words of Wisdom


Words of Wisdom
The world suffers a lot. Not because of the violence of the bad people, but because of the silence of good people!                                                    
                                                                                                 --Napoleon

Laughing faces do not mean that there is absence of sorrow. It means that they have the ability to deal with it.                                                 
                                                                                                 --Shakespeare

Opportunities are like sunrises, if you wait too long, you may miss them.
                                                                                                 --William Arthur

It is very easy to defeat someone, but it is very hard to win someone. 
                                                                                                 -- John Keats

You always pass failure on your way to success.                      
                                                                                                 --Mickey Rooney
Let me not defer doing kindness, for I shall not pass this way again.
                                                                                                 -- E.de Grellet

If I can stop one heart from breaking, l shall not live in vain.  
                                                                                                 --Emily Dickinson

Honour is the reward of virtue.                                                --Cicero

It is virtue and not birth that makes us noble.                          --J.F.Fletcher

No one can reach me by reading scriptures.                             
                                                                                 --God Sermonizer of Gita

Reading scriptures will empower one no more than reading about medicines will cure a patient of the illness.

It is through our righteous actions that his world is transformed. God gives us the wisdom to do so.

Friday, February 8, 2013

How to get source files from .apk file

How to get source files from .apk file

Android application package file (APK) is the file format used to distribute and install application software and middleware onto Google's Android operating system
We can now get java code from apk files with ease.
Following are steps to get java code from apk file.

Step 1:Renaming .apk file
Rename the .apk file with the extension .zip (suppose the file be "android.apk" then after renaming it becomes "android.apk.zip")
Step 2:Get the java files from apk
2.1 Now extract the renamed zip file(android.apk.zip) in specific folder, supposed that folder     
       name is "androidFolder".
2.2 Now Download dex2jar and extract that zip file in folder "androidFolder".
2.3 Now open command prompt and go to the folder path created in previous step and type 
       the command(for example folder path is c:\\androidFolder\dex2jar) 
      "dex2jar ../classes.dex" and press enter.This will generate "classes.dex.dex2jar" file in  
       the same folder.
2.4 Now  Download java decompiler and extract it and start(double click) jd-gui.exe
2.5 Now open jd-gui window browse the generated "classes.dex.dex2jar" file in 
       androidFolder, this will give you all the class files by src name.
2.6 Now from the File menu select "save all sources" this will generate a zip file named 
     "classes_dex2jar.src.zip" consisting of all packages and java files.
2.7 Now extract that zip file (classes_dex2jar.src.zip) and you will get all java files of the 
      application.
Above steps will generate java files.
To get xml files perform following steps.
Step 3:Getting xml files from apk
3.1 Download apktool and install it and extract both files and place it in the same folder (for 
      example "androidXmlFolder").
3.2 Place the .apk file in same folder (i.e androidXmlFolder)
3.3 Now open command prompt and goto the directory where apktool is stored (here 
      "androidXmlFolder") and type the following command "apktool if framework-res.apk" 
      Above command result should be "Framework installed ..."
3.4 Now in command prompt type the command "apktool d filename.apk" (where filename is name of apk file).
3.5 This will generate a folder of name filename in current directory (here androidXmlFolder) where all xml files will be stored in res\layout folder.
Dex to java files



Monday, January 28, 2013

NFC Android Tutorial

Overview

NFC (Near Field Communication) is set of standards that enable smartphones and similar devices to establish a radio communication*( requires a distance of 4cm or less to initiate a connection) and allows to transfer data such as text or numbers between two NFC enabled devices.
In practice, NFC enables simple and safe two- way interactions among electronic devices within a close proximity
NFC standards are  based on RFID (radio frequency identification) standards.

NFC

Device should be NFC enabled to use this technology


Nfc Features
•  Short range technology
                  –  Connection established when devices or tag close enough (5-10 cm)
                  –  Simple setup (instant configuration)
•  2-way communication
                  –  Not only reading like in contactless smart cards, but data exchange
•  Passive tags
                  –  No need for external power
                  –  Low-price
•  Security
                  –  Support secure element
                  –  Close proximity use brings some basic security
What  can we store in NFC tags?

We can store variety of data on NFC TAG. The actual amount of data varies depending on the type of NFC tag used - different tags have different memory capacities.  A standard Ultralight nfc tag can  store a URL of around 41 characters, while NTAG203   can store data around 132 characters.
Usually, this information is stored in a specific data format (NDEF - NFC data exchange format) so that it can be reliably read by most devices and mobile phones.

Nfc Modes

•  Read and write tags
•  Peer-to-peer
•  Card emulation

Android Support
          –  Read and write (excellent support)
P2P (limited)

Requirements for using NFC enabled application

Most Important requirement for a device is that it should have required hardware to support NFC feature
here is the list of NFC enabled mobile devices

Minimum API required

API level 9 only supports limited tag dispatch via Action_Tag_Discovered and only gives access to NDEF messages via the EXTRA_NDEF_MESSAGE extra. No other tag properties or I/O operations are accessible. API level 10 includes comprehensive reader/writer support as well as foreground NDEF pushing, and API level 14 provides an easier way to push NDEF messages to other devices with Android Beam and extra convenience methods to create NDEF records.

Permissions required for Android application to use NFC

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

<uses-sdk android:minSdkVersion="10"/>

<uses-feature android:name="android.hardware.nfc" android:required="true" />

Key Players

NfcManager  is the high level manager, used to obtain this device's NfcAdapter.
NfcAdapter  represents the device's NFC adapter, which is your entry-point to performing NFC operations
NdefMessage Represents NDEF data message, which is the standard format in which "records" carrying data are transmitted between devices and tags. Your application can receive these messages from ACTION_TAG_DISCOVERED ntent.
NdefRecord Represents a record, which is delivered in a NdefMessage and describes the type of data being shared and carries the data itself.
How NFC tags are read
Reading NDEF data from an NFC tag is handled with the tag dispatch system , which analyzes discovered NFC tags, appropriately categorizes the data, and starts an application that is interested in the categorized data. An application that wants to handle the scanned NFC tag can declare an intent filter and request to handle the data.

Enabling foreground
/**
* Enables foreground intent detection
*/
    public void enableForeground() {

        if(!foreground) {

            IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
            IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
            writeTagFilters = new IntentFilter[] {tagDetected, ndefDetected};
            nfcAdapter.enableForegroundDispatch(context, nfcPendingIntent, writeTagFilters, null);

            foreground = true;
        }
    }



Now we create a IntentFilter, to tell Android that our application is enabled to work on nfc tag (NfcAdapter.ACTION_TAG_DISCOVERED). We register our app with an intentFilter in the Manifest.

<activity android:name="com.example.activity.NfcReaderActivity" >
            <intent-filter>
                <action android:name="android.nfc.action.TAG_DISCOVERED" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
method to read nfc tag

/**
     * Reads the ndef messages from the given intent
     *
     * @param intent
     * @return true if messages were extracted
     */
    public boolean read(Intent intent) {
        Log.d(TAG, "Read intent");

        Parcelable[] messages = intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (messages != null) {
            NdefMessage[] ndefMessages = new NdefMessage[messages.length];
            for (int i = 0; i < messages.length; i++) {
                ndefMessages[i] = (NdefMessage) messages[i];
            }

            if (ndefMessages.length > 0) {
                listener.readNdefMessages(ndefMessages);

                return true;
            } else {
                listener.readNdefEmptyMessage();
            }
        } else {
            listener.readNonNdefMessage();
        }

        return false;
    }
­
Writing NFC tags
­
    public boolean write(final NdefMessage message, Intent intent) {
        final Tag extra = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Thread t = new Thread(new Runnable() {
            Tag tag = extra;

            @Override
            public void run() {
        NdefFormatable format = NdefFormatable.get(tag);
        if (format != null) {
            Log.d(TAG, "Write unformatted tag");
            try {
                format.connect();
                format.format(message);

                listener.wroteNdefUnformatted();

                        return;
            } catch (Exception e) {
                listener.writeNdefUnformattedFailed(e);
            }
                    finally{
                        try {
                            format.close();
                        } catch (IOException e) {
                            Log.d(TAG, "Cannot close connection to the tag.");
                        }
                    }
            Log.d(TAG, "Cannot write unformatted tag");
        } else {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                try {
                    Log.d(TAG, "Write formatted tag");

                    ndef.connect();
                    if (!ndef.isWritable()) {
                        Log.d(TAG, "Tag is not writeable");

                        listener.writeNdefNotWritable();

                                return;
                    }
                    if (ndef.getMaxSize() < message.toByteArray().length) {
                        Log.d(TAG,
                                "Tag size is too small, have "
                                        + ndef.getMaxSize() + ", need "
                                        + message.toByteArray().length);

                        listener.writeNdefTooSmall(
                                message.toByteArray().length, ndef.getMaxSize());

                                return;
                    }
                    ndef.writeNdefMessage(message);

                    listener.wroteNdefFormatted();

                            return;
                } catch (Exception e) {
                    listener.writeNdefFormattedFailed(e);
                }
            } else {
                listener.writeNdefCannotWriteTech();
            }
            Log.d(TAG, "Cannot write formatted tag");
        }

            }
        });

        t.run();
        return success;
    }

Sources:
 download the nfctools.jar file from here