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

ORMLite Android Tutorial

ORMLite provides a lightweight Object Relation Mapping between Java classes and SQL databases.

OVERVIEW

ORMLite provides a lightweight Object Relation Mapping between Java classes and SQL databases ORMLite supports JDBC connections to MySQL, Postgres, H2, SQLite, Derby, HSQLDB, Microsoft SQL Server. ORMLite also supports native database calls on Android Operating System.

Implementatin ORMLite with Android

To get started with ORMLite, We need to download the ORMLite jar files.These can be downloaded from ORMLite release page
Once we download ORMLite we need to add external library to our android project. Put the jar file into your project’s libs/ subdirectory.
We only need the ormlite-android-4.14.jar, not the ormlite-core or any other packages.
Getting Started with  ORMLite
Get started Ormlite we will need to create our own database helper class which should extend the OrmLiteSqliteOpenHelper class. This class creates and upgrades the database when the application is installed and also provide the DAO(Data Access Object) classes used by other classes. The helper class must implement the methods
onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource)
onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)
onCreate creates the database when app is first installed while onUpgrade handles the upgrading of the database tables when we upgrade our app to a new version.
The helper should be kept open across all activities in the app with the same SQLite database connection reused by all threads. If we open multiple connections to the same database, stale data and unexpected results may occur. It is recommended to use the OpenHelperManager to monitor the usage of the helper – it will create it on the first access, track each time a part of our code is using it, and then it will close the last time the helper is released.
Once we define our database helper and are managing it correctly, We will use it in our Activity classes. An easy way to use the OpenHelperManager is to extend OrmLiteBaseActivity for each of your activity classes – there is also OrmLiteBaseListActivity, OrmLiteBaseService, and OrmLiteBaseTabActivity. These classes provide a helper protected field and a getHelper() method to access the database helper whenever it is needed and will automatically create the helper in the onCreate() method and release it in the onDestroy() method.


Sample Database Helper 


import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
/**
* Database helper class used to manage the creation and upgrading of your
* database. This class also usually provides the DAOs used by the other classes.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// name of the database file for your application — change to something appropriate for your app
private static final String DATABASE_NAME = “scotchadmins”;
// any time you make changes to your database, you may have to increase the database version
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the any table
private Dao<DemoORMLite, Integer> DemoORMLiteDao = null;
private RuntimeExceptionDao<DemoORMLite, Integer> DemoORMLiteRuntimeDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* This is called when the database is first created. Usually you should
* call createTable statements here to create the tables that will store your data.
*/
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), “onCreate”);
TableUtils.createTable(connectionSource, DemoORMLite.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), “Can’t create database”, e);
throw new RuntimeException(e);
}
// here we try inserting data in the on-create as a test
RuntimeExceptionDao<DemoORMLite, Integer> dao = getDemoORMLiteDao();
String name = scotchadmins
// create some entries in the onCreate
long date = System.currentTimeMillis();
DemoORMLite demo = new DemoORMLite(name,date);
dao.create(demo);
Log.i(DatabaseHelper.class.getName(), “created new entries in onCreate: “);
}
/**
* This is called when the application is upgraded and it has a higher
* version number. This allows you to adjust the various data to match the
* new version number.
*/
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), “onUpgrade”);
TableUtils.dropTable(connectionSource, DemoORMLite.class, true);
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), “Can’t drop databases”, e);
throw new RuntimeException(e);
}
}
/**
* Returns the Database Access Object (DAO) for our SimpleData class. It
* will create it or just give the cached value.
*/
public Dao<DemoORMLite, Integer> getDao() throws SQLException {
if (DemoORMLiteDao == null) {
DemoORMLiteDao = getDao(DemoORMLite.class);
}
return DemoORMLiteDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
DemoORMLiteRuntimeDao = null;
}
}

Creating a Table in ORMLite


There are a few things to notice when we use ORMLite
First: We just annotate our class as a table and its members as fields and we’ re almost done with creating a table
The second thing to notice is that ORMLite handles all of the basic data types without any explicit work on your part (integers, strings, floats, dates, and more).

It is mandatory to have a no argument constructor in our class

public class DemoORMLite {
// Class name will be tablename Fields here
@DatabaseField(generatedId = true, canBeNull = false)
int _id;
@DatabaseField(canBeNull = true)
String first_name;
@DatabaseField(canBeNull = true)
String last_name;
@DatabaseField(canBeNull = true)
Date created;
DemoORMLite() {
}

public DemoORMLite(String name,long date) {
this.first_name = name;
this.last_name = “lastname”;
this.created = new Date(date);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(_id);
sb.append(“, “).append(first_name);
sb.append(“, “).append(last_name);
SimpleDateFormat dateFormatter = new SimpleDateFormat(
“MM/dd/yyyy HH:mm:ss.S”);
sb.append(“, “).append(dateFormatter.format(created));
return sb.toString();
}
}
}

Database Operations

Deleting a record in ormlite
DeleteBuilder assists in building sql DELETE statements for a particular table in a  database.
Sample Code that  deletes elements from table in field by arg
DatabaseHelper helper = OpenHelperManager.getHelper(App.getContext(), DatabaseHelper.class);
Dao dao = helper.getDao(YOUR_CLASS.class);
DeleteBuilder<CanteenLog, Integer> deleteBuilder = dao.deleteBuilder();
deleteBuilder.where().eq(“FIELD_NAME”, arg);
deleteBuilder.delete();

Query in ORMLite

1.Query for all
returns the list of all records in the table we have inbuild function queryForAll();
// get our dao
RuntimeExceptionDao<DemoORMLite, Integer> DemoORMLiteDao = getHelper().getDemoORMLiteDao ();
// query for all of the data objects in the database
List<SimpleData> list = simpleDao.queryForAll();
2.Query for id
returns the record corresponding to given id we have inbuild function queryForId(id);
Sample code
TEntity entity = this.dao.queryForId(id)
3.Query for particular field name
here we query for field “lastname” and it returns list of records that have last_name =”lastname”

public List<DemoORMLite> RetrieveByLastName(String lastname)  throws SQLException {
QueryBuilder<TEntity, Integer> queryBuilder = dao.queryBuilder();
List<TEntity> list;
queryBuilder.where().eq(“last_name”, lastname);
list = queryBuilder.query();
return list;
}