Thursday, 23 April 2015

Getting Unique Device ID of an Android Smartphone

Sometimes it is required during Android application development to get the unique id of the Android based smartphone device. This is necessary in cases when the user wants to track the unique device installations of the application.
This is also useful in cases where the Android developer wants to send Push messages to only few specific devices. So over here it becomes necessary to have a UDID for every device.
In Android there are many alternatives to UDID of the device. Some of the methods to get the UDID in android application are listed below with its advantages and disadvantages and any necessary permissions for getting the device ID.
  1. The IMEI: (International Mobile Equipment Identity)
  2. The Android ID
  3. The WLAN MAC Address string
  4. The Bluetooth Address string

1) The IMEI: (International Mobile Equipment Identity)

The IMEI Number is a very good and primary source to get the device ID. It is unique for each and every device and is dependent on the device Hardware. So it is also unique for each and every device and it is permanent till the lifetime of the device.
The code snippet to get the Device IMEI is as below,
For this your application will require the permission “android.permission.READ_PHONE_STATE” given in the manifest file.
Advantages of using IMEI as Device ID:
  • The IMEI is unique for each and every device.
  • It remains unique for the device even if the application is re-installed or if the device is rooted or factory reset.
Disadvantages of using IMEI as Device ID:
  • IMEI is dependent on the Simcard slot of the device, so it is not possible to get the IMEI for the devices that do not use Simcard.
  • In Dual sim devices, we get 2 different IMEIs for the same device as it has 2 slots for simcard.

2) The Android ID

The Android_ID is a unique 64 bit number that is generated and stored when the device is first booted. The Android_ID is wiped out when the device is Factory reset and new one gets generated.
The code to get the Android_ID is shown below,
Advantages of using Android_ID as Device ID:
  • It is unique identifier for all type of devices (smart phones and tablets).
  • No need of any permission.
  • It will remain unique in all the devices and it works on phones without Simcard slot.
Disadvantages of using Android_ID as Device ID:
  • If Android OS version is upgraded by the user then this may get changed.
  • The ID gets changed if device is rooted or factory reset is done on the device.
  • Also there is a known problem with a Chinese manufacturer of android device that some devices have same Android_ID.

3) The WLAN MAC Address string

We can get the Unique ID for android phones using the WLAN MAC address also. The MAC address is unique for all devices and it works for all kinds of devices.
The code snippet to get the WLAN MAC address for a device is as shown below,
Your application will require the permission “android.permission.ACCESS_WIFI_STATE” given in the manifest file.
Advantages of using WLAN MAC address as Device ID:
  • It is unique identifier for all type of devices (smart phones and tablets).
  • It remains unique if the application is reinstalled
Disadvantages of using WLAN MAC address as Device ID:
  • If device doesn’t have wifi hardware then you get null MAC address, but generally it is seen that most of the Android devices have wifi hardware and there are hardly few devices in the market with no wifi hardware.

4) The Bluetooth Address string

We can get the Unique ID for android phones using the Bluetooth device also. The Bluetooth device address is unique for each device having Bluetooth hardware.
The code snippet to get the Bluetooth device address is as given below,
To get the above code, your application needs the permission “android.permission.BLUETOOTH” given in the manifest file.
Advantages of using Bluetooth device address as Device ID:
It is unique identifier for all type of devices (smart phones and tablets).
There is generally a single Bluetooth hardware in all devices and it doesn’t gets changed.
Disadvantages of using Bluetooth device address as Device ID:
If device hasn’t bluetooth hardware then you get null.
As per me these are few of the best possible ways to get the Unique Device ID for Android smartphone device and their pros and cons of using it. Now it is upto you to decide which method to use based on the Android application development requirements.

Monday, 20 April 2015

Android Tip - Hide App Icon in Launcher

You may have an application that contains a broadcast receiver and for some reasons you want to hide the application icon in the Launcher after it has been installed (so that the user doesn’t know the app existed).

Programmatically Hiding the Icon


If you want the application icon to be visible after installation and hide it programmatically afterwards, you can use the following code snippets:

    PackageManager p = getPackageManager();
    p.setComponentEnabledSetting(getComponentName(),
        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP);
   
When the above statements are executed, the application icon in the Launcher will disappear after a while.

Declaratively Hiding the Icon

The easist way to hide your application icon from the Launcher is to remove theandroid.intent.category.LAUNCHER category from your app’s AndroidManifest.xml file. However, simply doing so will also render your broadcast receiver useless – it won’t respond to your broadcasts.

To fix this, you need to also add in the android.intent.category.DEFAULT category, like this:

        <activity
            android:name=
            "net.learn2develop.locationmonitor.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name=
                    "android.intent.action.MAIN" />                              
                <category android:name=
                    "android.intent.category.DEFAULT" />
               
                <!—
                <category android:name=
                    "android.intent.category.LAUNCHER" />
                -->
            </intent-filter>
        </activity>


The application icon will then no longer appear in the Launcher.

Sunday, 19 April 2015

Repeating Background Textures in Android


  • Pick something from Subtle Patterns, e.g. irongrip.png and drop it in your drawable-hdpi folder
  • Make a BitmapDrawable, e.g. irongrip_repeating.xml
1234
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/irongrip"
android:tileMode="repeat" />
  • Apply it to a View
123456
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/irongrip_repeating"
android:orientation="vertical">
</LinearLayout>
view rawmain.xml hosted with ❤ by GitHub
The result:
A pretty simple way to spruce up an app, just don't go overboard. Happy hacking!

Saturday, 18 April 2015

Android SQLite Database Tutorial

.
addContact()
    // Adding new contact
public void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}

⇒Reading Row(s)

The following method getContact() will read single contact row. It accepts id as parameter and will return the matched row from the database.
getContact()
    // Getting single contact
public Contact getContact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
            KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();
    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2));
    // return contact
    return contact;
}
getAllContacts() will return all contacts from database in array list format of Contact class type. You need to write a for loop to go through each contact.
getAllContacts()
    // Getting All Contacts
 public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    // return contact list
    return contactList;
}
getContactsCount() will return total number of contacts in SQLite database.
getContactsCount()
// Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        // return count
        return cursor.getCount();
    }

⇒Updating Record

updateContact() will update single contact in database. This method accepts Contact class object as parameter.
updateContact()
    // Updating single contact
public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhoneNumber());
    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
}

⇒Deleting Record

deleteContact() will delete single contact from database.
deleteContact()
    // Deleting single contact
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}

Complete DatabaseHandler.java Code:

DatabaseHandler.java
package com.androidhive.androidsqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
        // Create tables again
        onCreate(db);
    }
    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */
    // Adding new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }
    // Getting single contact
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        // return contact
        return contact;
    }
     
    // Getting All Contacts
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
        // return contact list
        return contactList;
    }
    // Updating single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());
        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }
    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }
    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        // return count
        return cursor.getCount();
    }
}

Usage:

AndroidSQLiteTutorialActivity
package com.androidhive.androidsqlite;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class AndroidSQLiteTutorialActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        DatabaseHandler db = new DatabaseHandler(this);
         
        /**
         * CRUD Operations
         * */
        // Inserting Contacts
        Log.d("Insert: ", "Inserting ..");
        db.addContact(new Contact("Ravi", "9100000000"));       
        db.addContact(new Contact("Srinivas", "9199999999"));
        db.addContact(new Contact("Tommy", "9522222222"));
        db.addContact(new Contact("Karthik", "9533333333"));
         
        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
        List<Contact> contacts = db.getAllContacts();      
         
        for (Contact cn : contacts) {
            String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
                // Writing Contacts to log
        Log.d("Name: ", log);
    }
    }
}

Android Log Cat Report:

I am writing output to Log report. You can see your log report by going to Windows ⇒ Show View ⇒ Other.. ⇒ Android ⇒ Log Cat.
Android Log Cat
Android Log Cat
Android Output log report