Friday, August 26, 2016

The Stock Span Problem Solution in Java

The Stock Span Problem

The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock’s price for all n days.

The span of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day.

For example, 
if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding 7 days are {1, 1, 1, 2, 1, 4, 6}

Solution:

Traverse the input price array. For every element being visited, traverse elements on left of it and increment the span value of it while elements on the left side are smaller.

Code:

import java.util.Stack;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class TheStockSpanProblem {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int price[] = {10, 4, 5, 90, 120, 80};
stockSpanProblem(price);

}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static int[] stockSpanProblem(int[] arr)
{
Stack<Integer> s = new Stack();
Stack<Integer> s2 = new Stack();
int[] returned_arr = new int[arr.length];
int temp;
int count;
for(int i = 0;i < arr.length; i++)
{
 count = 1;
//to push elements inside it until larger element comes
if (s.empty())

s.push(arr[i]);

if (s.peek() > arr[i])
{
 s.push(arr[i]);
}
else
{
 while (!s.empty() && s.peek() < arr[i])
 {
temp = s.pop();
s2.push(temp);
count ++;
 }
s.push(arr[i]);//push this element
while (!s2.empty())
{
 s.push(s2.pop());
}//so s2 empty at last
}
returned_arr[i] = count;
System.out.println(returned_arr[i]);
  }
   return returned_arr;
}
}

Output:


1 1 2 4 5 1

But this solution is inefficient.Can be a better solution than this.

Time Complexity: O(n). It seems more than O(n) at first look. If we take a closer look, we can observe that every element of array is added and removed from stack at most once. So there are total 2n operations at most. Assuming that a stack operation takes O(1) time, we can say that the time complexity is O(n).

Auxiliary Space: O(n) in worst case when all elements are sorted in decreasing order.

Wednesday, August 17, 2016

Bucket Sort Java Implementation

Bucket Sort

Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the following problem.
Sort a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. How do we sort the numbers efficiently?

A simple way is to apply a comparison based sorting algorithm. The lower bound for Comparison based sorting algorithm (Merge Sort, Heap Sort, Quick-Sort .. etc) is Ω(n Log n), i.e., they cannot do better than nLogn.
Can we sort the array in linear time? Counting sort can not be applied here as we use keys as index in counting sort. Here keys are floating point numbers.

The idea behind the bucket sort:

bucketSort(arr[], n)

1) Create n empty buckets (Or lists).
2) Do following for every array element arr[i].
 a) Insert arr[i] into bucket[n*array[i]]
3) Sort individual buckets using insertion sort.
4) Concatenate all sorted buckets.

So, Bucket sort or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a distribution sort, and is a cousin of radix sort in the most to least significant digit flavor. Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons and therefore can also be considered a comparison sort algorithm. The computational complexity estimates involve the number of buckets.

Bucket sort works as follows:

Set up an array of initially empty "buckets".
Scatter: Go over the original array, putting each object in its bucket.
Sort each non-empty bucket.
Gather: Visit the buckets in order and put all elements back into the original array.

Optimizations:

A common optimization is to put the unsorted elements of the buckets back in the original array first, then run insertion sort over the complete array; because insertion sort's run-time is based on how far each element is from its final position, the number of comparisons remains relatively small, and the memory hierarchy is better exploited by storing the list contiguously in memory.

Time Complexity: If we assume that insertion in a bucket takes O(1) time then steps 1 and 2 of the above algorithm clearly take O(n) time. The O(1) is easily possible if we use a linked list to represent a bucket (In the following code, C++ vector is used for simplicity). Step 4 also takes O(n) time as there will be n items in all buckets.

Sample Code :

import java.util.Arrays;
/**
 * @author Abhinaw.Tripathi
 *
 */
public class BucketSortApp
{
 public static void sort(int[] a, int maxVal)
 {
     int [] bucket=new int[maxVal+1];

     for (int i=0; i<bucket.length; i++)
     {
        bucket[i]=0;
     }

     for (int i=0; i<a.length; i++)
     {
        bucket[a[i]]++;
     }

     int outPos=0;
     for (int i=0; i<bucket.length; i++)
     {
        for (int j=0; j<bucket[i]; j++)
        {
           a[outPos++]=i;
        }
     }
  }

public static void main(String[] args)
{
 int maxVal=5;
          int [] data= {5,3,0,2,4,1,0,5,2,3,1,4};

     System.out.println("Before: " + Arrays.toString(data));
     sort(data,maxVal);
     System.out.println("After:  " + Arrays.toString(data));
}

}

Result:

Before: [5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4]
After:  [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]


Shell Sort Algorithm implementation in java


Shell sort, also known as Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort).The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. Starting with far apart elements, it can move some out-of-place elements into position faster than a simple nearest neighbor exchange.
The running time of Shell sort is heavily dependent on the gap sequence it uses.

Pseudocode: 

# Sort an array a[0...n-1].
gaps = [701, 301, 132, 57, 23, 10, 4, 1]

# Start with the largest gap and work down to a gap of 1
[[foreach]] (gap in gaps)
{
    # Do a gapped insertion sort for this gap size.
    # The first gap elements a[0..gap-1] are already in gapped order
    # keep adding one more element until the entire array is gap sorted
    for (i = gap; i < n; i += 1)
    {
        # add a[i] to the elements that have been gap sorted
        # save a[i] in temp and make a hole at position i
        temp = a[i]
        # shift earlier gap-sorted elements up until the correct location for a[i] is found
        for (j = i; j >= gap and a[j - gap] > temp; j -= gap)
        {
            a[j] = a[j - gap]
        }
        # put temp (the original a[i]) in its correct location
        a[j] = temp
    }
}

So,Shell Sort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sub-lists of every h’th element is sorted.

Time Complexity:

 Time complexity of above implementation of shell-sort is O(n2). In the above implementation gap is reduce by half in every iteration. There are many other ways to reduce gap which lead to better time complexity.


Sample Code:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class ShellSortApp
{
static void printArray(int arr[])
       {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

    /* function to sort arr using shellSort */
    int sort(int arr[])
    {
        int n = arr.length;

        // Start with a big gap, then reduce the gap
        for (int gap = n/2; gap > 0; gap /= 2)
        {
            for (int i = gap; i < n; i += 1)
            {
                int temp = arr[i];
                int j;
                for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
                    arr[j] = arr[j - gap];

                arr[j] = temp;
            }
        }
        return 0;
    }

public static void main(String[] args)
{
int arr[] = {12, 34, 54, 2, 3};
       System.out.println("Array before sorting");
       printArray(arr);

       ShellSortApp ob = new ShellSortApp();
       ob.sort(arr);

       System.out.println("Array after sorting");
       printArray(arr);
}

}

Result: 

Array before sorting
12 34 54 2 3 
Array after sorting
2 3 12 34 54 

Tuesday, August 16, 2016

Comb Sort Algo in Java

The basic idea is to eliminate turtles, or small values near the end of the list, since in a bubble sort these slow the sorting down tremendously. Rabbits, large values around the beginning of the list, do not pose a problem in bubble sort.

In bubble sort, when any two elements are compared, they always have a gap (distance from each other) of 1. The basic idea of comb sort is that the gap can be much more than 1. The inner loop of bubble sort, which does the actual swap, is modified such that gap between swapped elements goes down (for each iteration of outer loop) in steps of shrink factor: [ input size / shrink factor, input size / shrink factor^2, input size / shrink factor^3, ..., 1 ].

The gap starts out as the length of the list being sorted divided by the shrink factor (generally 1.3; see below) and one pass of the aforementioned modified bubble sort is applied with that gap. Then the gap is divided by the shrink factor again, the list is sorted with this new gap, and the process repeats until the gap is 1. At this point, comb sort continues using a gap of 1 until the list is fully sorted. The final stage of the sort is thus equivalent to a bubble sort, but by this time most turtles have been dealt with, so a bubble sort will be efficient.

The shrink factor has a great effect on the efficiency of comb sort. 1.3 has been suggested as an ideal shrink factor by the authors of the original article after empirical testing on over 200,000 random lists. A value too small slows the algorithm down by making unnecessarily many comparisons, whereas a value too large fails to effectively deal with turtles.

So,Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap and performs better than Bublle Sort.

The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200,000 random lists).

Although, it works better than Bubble Sort on average, worst case remains O(n2).


Code Implementation:

import java.util.*;

public class CombSort
 {

    public static void sort(int[] array, int size)
    {
        int gap = size; // The distance between elements being compared
        boolean swapped = true;
        int i; // Our index

        while (gap > 1 || swapped)
        {
            if (gap > 1) {
                gap = (int)(gap / 1.3);
            }

            if (gap == 9 || gap == 10)
            {
                gap = 11;
            }

            i = 0;
            swapped = false;

            // Loop through comparing numbers a gap-length apart.
            // If the first number is bigger than the second, swap them.
            while (i + gap < size)
            {
                if (array[i] > array[i+gap])
                {
                    swap(array, i, i+gap);
                    swapped = true;
                }
                i++;
            }
        }
    }

    public static void swap(int[] list, int i, int j)
    {
        int temp = list[i];
        list[i] = list[j];
        list[j] = temp;
    }

    public static String input(String s)
    {    
        System.out.print(s);
        Scanner scan = new Scanner(System.in);
        return scan.next();
    }

    public static void main(String[] args) {
        /* Ask the user how many numbers of what range
        should be sorted by the algorithm and if they want to see the array */

        int ammount = Integer.parseInt( input("How many numbers shall be generated? ") );
        int min = Integer.parseInt( input("Min value of numbers: ") );
        int max = Integer.parseInt( input("Max value of numbers: ") );
        boolean show_array = input("Would you like to see the sorted and unsorted list?(y/n) ").equals("y");
       
        int[] numbers = new int[ammount];
        Random rand = new Random();
        for (int n=0; n < ammount; n++)
        {
            numbers[n] = rand.nextInt(max - min + 1) + min;
        }

        if (show_array)
        {
            System.out.println("__UNSORTED ARRAY__");
            System.out.println(Arrays.toString(numbers));
        }
        sort(numbers, ammount);
        if (show_array)
        {
            System.out.println("__SORTED ARRAY__");
            System.out.println(Arrays.toString(numbers));
        }

    }
}

Output:

How many numbers shall be generated?
4
Min value of numbers: 2
Max value of numbers: 8
Would you like to see the sorted and unsorted list?(y/n) y
__UNSORTED ARRAY__
[5, 3, 8, 6]
__SORTED ARRAY__
[3, 5, 6, 8]


Another Implementation:

import java.util.Scanner;

public class CombSort
{
    public static void main(String[] args)
    {
        int i;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter no elements you want (Size):");
        int size = sc.nextInt();
        int[] a = new int[size];
        System.out.println("Please enter the " + size + " elements:");
        for (i = 0; i < size; i++)
        {
            a[i] = sc.nextInt();
        }
        System.out.println("Sorted array is :");
        CombSort cs = new CombSort(a);
        for (i = 0; i < size; i++)
        {
            System.out.printf("%d\t", a[i]);
        }
    }
    private final int[] a;

    private CombSort(int[] b)
    {
        this.a = b;
        combSort(a.length);
    }

    private void combSort(int size)
    {
        float shrink = 1.3f;
        int swap;
        int i, gap = size;
        boolean swapped = false;
        while ((gap > 1) || swapped)
        {
            if (gap > 1)
            {
                gap = (int) ((float) gap / shrink);
            }
            swapped = false;
            for (i = 0; gap + i < size; ++i)
            {
                if (a[i] - a[i + gap] > 0)
                {
                    swap = a[i];
                    a[i] = a[i + gap];
                    a[i + gap] = swap;
                    swapped = true;
                }
            }
        }
    }
}

Result:

Enter no elements you want (Size):
4
Please enter the 4 elements:
12
23
08
44
Sorted array is :
8 12 23 44

Pigeonhole Sort Algorithm Implementation in Java

Pigeonhole Sort Algorithm-

Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements (n) and the length of the range of possible key values (N) are approximately the same. It requires O(n + N) time. It is similar to counting sort, but differs in that it "moves items twice: once to the bucket array and again to the final destination [whereas] counting sort builds an auxiliary array then uses the array to compute each item's final destination and move the item there.

It requires O(n + Range) time where n is number of elements in input array and ‘Range’ is number of possible values in array.

The pigeonhole algorithm works as follows:

1)Given an array of values to be sorted, set up an auxiliary array of initially empty "pigeonholes," one pigeonhole for each key through the range of the original array.

2)Going over the original array, put each value into the pigeonhole corresponding to its key, such that each pigeonhole eventually contains a list of all values with that key.

3)Iterate over the pigeonhole array in order, and put elements from non-empty pigeonholes back into the original array.

                                                       

Example:

Suppose we were sorting these value pairs by their first element:

(5, "hello")
(3, "pie")
(8, "apple")
(5, "king")

For each value between 3 and 8 we set up a pigeonhole, then move each element to its pigeonhole:

3: (3, "pie")
4:
5: (5, "hello"), (5, "king")
6:
7:
8: (8, "apple")

We then iterate over the pigeonhole array in order and move them back to the original list.

The difference between pigeonhole sort and counting sort is that in counting sort, the auxiliary array does not contain lists of input elements, only counts:

3: 1
4: 0
5: 2
6: 0
7: 0
8: 1

Using this information we can perform a series of exchanges on the input array that puts it in order, moving items only once.

For arrays where N is much larger than n, bucket sort is a generalization that is more efficient in space and time.

Code Example implementation in Java:

import java.util.Arrays;
/**
 * @author Abhinaw.Tripathi
 *
 */
public class PigeonholeSortApp
{

public static void pigeonholesort(int arr[],int n)
{
int min=arr[0];
int max=arr[0];

for(int a=0;a<n;a++)
{
if(arr[a]>max)
max=arr[a];
if(arr[a]<min)
min=arr[a];
}

int range=max-min+1;
int[] phole=new int[range];
Arrays.fill(phole, 0);

for(int i=0;i<n;i++)
phole[arr[i]-min]++;

int index=0;

for(int j=0;j<range;j++)
while(phole[j]-->0)
arr[index++]=j+min;

}

public void printArray(int arr[])
{
        int n = arr.length;
        for(int i=0 ; i<n ; i++)
            System.out.print(arr[i]+" ");
    }
   
@SuppressWarnings("static-access")
public static void main(String[] args)
{
   PigeonholeSortApp sort = new PigeonholeSortApp();
          int[] arr = {82,37,61,21,34,92,12,19,42,37,55,72,86};
          System.out.println("Before : ");
          sort.printArray(arr);
          System.out.println("\nAfter : ");
          sort.pigeonholesort(arr,arr.length);
          sort.printArray(arr);
}

}

Result:

Before :
82 37 61 21 34 92 12 19 42 37 55 72 86
After :
12 19 21 34 37 37 42 55 61 72 82 86 92

Pigeonhole sort has limited use as requirements are rarely met. For arrays where range is much larger than n, bucket sort is a generalization that is more efficient in space and time.



Thursday, August 11, 2016

Beacons Android Integration Code Example continue....

For this you need to understand few major things

1)Estimote Beacon Library
2)App Id and Token Id
3)Need to give reference the library in the gradle file
4)The default beacon id is B9407F30-F5F8-466E-AFF9-25556B57FE6D

Manifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.beacon.testing">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application 
       android:name=".MyApplication"
        android:allowBackup="true"  
      android:icon="@drawable/becon"   
     android:label="@string/app_name" 
       android:supportsRtl="true"   
     android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


BeaconID.java :

import com.estimote.sdk.Region;
import java.util.UUID;

public class BeaconID
{

    private UUID proximityUUID;
    private int major;
    private int minor;

    public BeaconID(UUID proximityUUID, int major, int minor) {
        this.proximityUUID = proximityUUID;
        this.major = major;
        this.minor = minor;
    }

    public BeaconID(String UUIDString, int major, int minor) {
        this(UUID.fromString(UUIDString), major, minor);
    }

    public UUID getProximityUUID() {
        return proximityUUID;
    }

    public int getMajor() {
        return major;
    }

    public int getMinor() {
        return minor;
    }

    public Region toBeaconRegion() {
        return new Region(toString(), getProximityUUID(), getMajor(), getMinor());
    }

    public String toString() {
        return getProximityUUID().toString() + ":" + getMajor() + ":" + getMinor();
    }

    @Override    public int hashCode() {
        return toString().hashCode();
    }

    @Override    public boolean equals(Object o) {
        if (o == null) {
            return false;
        }

        if (o == this) {
            return true;
        }

        if (getClass() != o.getClass()) {
            return super.equals(o);
        }

        BeaconID other = (BeaconID) o;

        return getProximityUUID().equals(other.getProximityUUID())
                && getMajor() == other.getMajor()
                && getMinor() == other.getMinor();
    }
}

BeaconNotificationsManager.java :

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class BeaconNotificationsManager{

    private static final String TAG = "BeaconNotifications";

    private BeaconManager beaconManager;

    private List<Region> regionsToMonitor = new ArrayList<>();
    private HashMap<String, String> enterMessages = new HashMap<>();
    private HashMap<String, String> exitMessages = new HashMap<>();
    private Context context;
    private int notificationID = 0;

    public BeaconNotificationsManager(final Context context) {
        this.context = context;
        beaconManager = new BeaconManager(context);
        beaconManager.setMonitoringListener(new BeaconManager.MonitoringListener() {
            @Override            public void onEnteredRegion(Region region, List<Beacon> list) {
                Log.d(TAG, "onEnteredRegion: " + region.getIdentifier());
                Toast.makeText(context,"onEnteredRegion"+ region.getIdentifier(),Toast.LENGTH_LONG).show();
                MyApplication.identifier=""+region.getIdentifier();
                MyApplication.major=""+region.getMajor();
                MyApplication.minor=""+region.getMinor();
                MyApplication.proximity=""+region.getProximityUUID();
                Log.v(TAG,MyApplication.identifier+":"+ MyApplication.major+":"+ MyApplication.minor+":"+MyApplication.proximity);
                String message = enterMessages.get(region.getIdentifier());
                if (message != null) {
                    showNotification(message);
                }
            }

            @Override            public void onExitedRegion(Region region) {
                Log.d(TAG, "onExitedRegion: " + region.getIdentifier());
                String message = exitMessages.get(region.getIdentifier());
                if (message != null) {
                    showNotification(message);

                }
            }
        });
    }

    public void addNotification(BeaconID beaconID, String enterMessage, String exitMessage) {
        Region region = beaconID.toBeaconRegion();
        enterMessages.put(region.getIdentifier(), enterMessage);
        exitMessages.put(region.getIdentifier(), exitMessage);
        regionsToMonitor.add(region);
    }

    public void startMonitoring() {
        beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
            @Override            public void onServiceReady() {
                for (Region region : regionsToMonitor) {
                    beaconManager.startMonitoring(region);
                }
            }
        });
    }

    private void showNotification(String message)
    {
        Toast.makeText(context,message,Toast.LENGTH_LONG).show();

        Log.v("BeaconNotificationManager","Message is: "+ message);
        Intent resultIntent = new Intent(context, MainActivity.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle("Beacon Notifications")
                .setContentText(message)
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentIntent(resultPendingIntent);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(notificationID++, builder.build());
    }

}

MainActivity.java :

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.estimote.sdk.SystemRequirementsChecker;

public class MainActivity extends AppCompatActivity
{
    private TextView tvDevice,tvDetails;
    private ImageView iv_becon;
    private static final String TAG = "MainActivity";

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

    @Override    protected void onResume()
    {
        super.onResume();
        setTextDetails();
    }

    private void initView()
    {
        tvDevice = (TextView) findViewById(R.id.textView);
        iv_becon = (ImageView) findViewById(R.id.iv_becon);
        tvDetails=(TextView)findViewById(R.id.tvBeaconDetails);
    }

    private void startSearching()
    {
                MyApplication app = (MyApplication) getApplication();
                if (!SystemRequirementsChecker.checkWithDefaultDialogs(MainActivity.this))
                {
                    Log.e(TAG, "Can't scan for beacons, some pre-conditions were not met");
                    Log.e(TAG, "Read more about what's required at: http://estimote.github.io/Android-SDK/JavaDocs/com/estimote/sdk/SystemRequirementsChecker.html");
                    Log.e(TAG, "If this is fixable, you should see a popup on the app's screen right now, asking to enable what's necessary");
                }
                else if (!app.isBeaconNotificationsEnabled())
                {
                    Log.d(TAG, "Enabling beacon notifications");
                    app.enableBeaconNotifications();
                }
    }

    private void setTextDetails()
    {
        tvDevice.setText("Becon Found");
        iv_becon.setVisibility(View.VISIBLE);
        tvDetails.setText("Major:: "+MyApplication.major + "\n" + "Minor:: " +MyApplication.minor + "\n" + "Proximity:: " +MyApplication.proximity +"\n" + "Identifier:: " +MyApplication.identifier);
    }

}

MyApplication.java :

import android.app.Application;
import com.estimote.sdk.EstimoteSDK;

public class MyApplication extends Application
{
    private boolean beaconNotificationsEnabled = false;
    public static String identifier="";
    public static String major="";
    public static String minor="";
    public static String proximity="";

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

        // TODO: put your App ID and App Token here        // You can get them by adding your app on https://cloud.estimote.com/#/apps        EstimoteSDK.initialize(getApplicationContext(), "notificationestimote-ksu", "a74e58eacb5007271a789d6aa3f5197c");

        // uncomment to enable debug-level logging        // it's usually only a good idea when troubleshooting issues with the Estimote SDK        EstimoteSDK.enableDebugLogging(true);
    }

    public void enableBeaconNotifications() {
        if (beaconNotificationsEnabled) { return; }

        BeaconNotificationsManager beaconNotificationsManager = new BeaconNotificationsManager(this);

        beaconNotificationsManager.addNotification(
                // TODO: replace with UUID, major and minor of your own beacon                new BeaconID("B9407F30-F5F8-466E-AFF9-25556B57FE6D", 60454, 28798),
                "I am found by Application.",
                "Goodbye, world.");
        beaconNotificationsManager.startMonitoring();
        beaconNotificationsEnabled = true;
    }

    public boolean isBeaconNotificationsEnabled() {
        return beaconNotificationsEnabled;
    }
}


gradle file: 


apply plugin: 'com.android.application'
android {
    compileSdkVersion 24 
   buildToolsVersion "24.0.0"
    defaultConfig {
        applicationId "com.beacon.testing" 
       minSdkVersion 15 
       targetSdkVersion 24
        versionCode 1 
       versionName "1.0" 
   }
    buildTypes {
        release {
            minifyEnabled false    
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12' 
   compile 'com.android.support:appcompat-v7:24.0.0'  
  compile files('libs/estimote-sdk-javadoc.jar')
    compile 'com.estimote:sdk:0.11.0@aar' 
   compile 'com.google.android.gms:play-services-appindexing:8.1.0'}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.beacon.testing.MainActivity"    android:background="@drawable/backgrpound"    >
    <TextView       
 android:id="@+id/textView"  
      android:layout_width="wrap_content"  
      android:layout_height="wrap_content" 
       android:layout_alignParentBottom="true"  
      android:layout_centerHorizontal="true"   
     android:textStyle="bold"  
      android:textSize="20dp"     
   android:text="Searching..." />

    <ImageView  
      android:id="@+id/iv_becon"   
     android:layout_width="80dp"   
     android:layout_height="60dp"    
    android:background="@drawable/becon"  
      android:layout_centerInParent="true" 
       android:layout_alignParentEnd="true"  
      android:visibility="gone"       
 android:layout_alignParentRight="true" />

    <TextView 
       android:id="@+id/tvBeaconInfo" 
       android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"  
      android:layout_marginTop="10dp"
        android:textStyle="bold"  
      android:textSize="21dp"    
    android:textColor="@android:color/holo_red_light"  
      android:text="Beacon Information" />
    <TextView   
     android:id="@+id/tvBeaconDetails" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
      android:layout_below="@+id/tvBeaconInfo" 
       android:layout_centerHorizontal="true" 
       android:layout_marginTop="10dp"
        android:textColor="@android:color/holo_blue_dark" 
       android:textStyle="normal" 
       android:textSize="15dp"  
      android:text="Beacon Details" />


</RelativeLayout>

Output Should look like this...



Beacons Android Integration Tutorials

What is Beacons?

Well, Beacons are a solution. Beacons are a low-cost piece of hardware — small enough to attach to a wall or counter top — that use battery-friendly, low-energy Bluetooth connections to transmit messages or prompts directly to a smartphone or tablet.

Beacons can also be combined with semaphoric or other indicators to provide important information, such as the status of an airport, by the color and rotational pattern of its airport beacon, or of pending weather as indicated on a weather beacon mounted at the top of a tall building or similar site. When used in such fashion, beacons can be considered a form of optical telegraphy.

The term iBeacon and Beacon are often used interchangeably. iBeacon is the name for Apple’s technology standard, which allows Mobile Apps (running on both iOS and Android devices) to listen for signals from beacons in the physical world and react accordingly. In essence, iBeacon technology allows Mobile Apps to understand their position on a micro-local scale, and deliver hyper-contextual content to users based on location. The underlying communication technology is Bluetooth Low Energy.

What is Bluetooth Low Energy (BLE)?

Bluetooth Low Energy is a wireless personal area network technology used for transmitting data over short distances. As the name implies, it’s designed for low energy consumption and cost, while maintaining a communication range similar to that of its predecessor, Classic Bluetooth.

How is BLE different from Regular Bluetooth?

Power Consumption: Bluetooth LE, as the name hints, has low energy requirements. It can last up to 3 years on a single coin cell battery.
Lower Cost: BLE is 60-80% cheaper than traditional Bluetooth.
Application: BLE is ideal for simple applications requiring small periodic transfers of data. Classic Bluetooth is preferred for more complex applications requiring consistent communication and more data throughput.

How does BLE communication work?

BLE communication consists primarily of “Advertisements”, or small packets of data, broadcast at a regular interval by Beacons or other BLE enabled devices via radio waves.

BLE Advertising is a one-way communication method. Beacons that want to be “discovered” can broadcast, or “Advertise” self-contained packets of data in set intervals. These packets are meant to be collected by devices like smartphones, where they can be used for a variety of smartphone applications to trigger things like push messages, app actions, and prompts.

Apple’s iBeacon standard calls for an optimal broadcast interval of 100 ms.  Broadcasting more frequently uses more battery life but allows for quicker discovery by smartphones and other listening devices.

Standard BLE has a broadcast range of up to 100 meters, which make Beacons ideal for indoor location tracking and awareness.


How does iBeacon use BLE communication?

With iBeacon, Apple has standardized the format for BLE Advertising. Under this format, an advertising packet consists of four main pieces of information.

UUID: This is a 16 byte string used to differentiate a large group of related beacons. For example, if Coca-Cola maintained a network of beacons in a chain of grocery stores, all Coca-Cola beacons would share the same UUID. This allows Coca-Cola’s dedicated smartphone app to know which beacon advertisements come from Coca-Cola-owned beacons.

Major: This is a 2 byte string used to distinguish a smaller subset of beacons within the larger group. For example, if Coca-Cola had four beacons in a particular grocery store, all four would have the same Major. This allows Coca-Cola to know exactly which store its customer is in.

Minor: This is a 2 byte string meant to identify individual beacons. Keeping with the Coca-Cola example, a beacon at the front of the store would have its own unique Minor. This allows Coca-Cola’s dedicated app to know exactly where the customer is in the store.

Tx Power: This is used to determine proximity (distance) from the beacon. How does this work? TX power is defined as the strength of the signal exactly 1 meter from the device. This has to be calibrated and hard-coded in advance. Devices can then use this as a baseline to give a rough distance estimate.

Example:

A beacon broadcasts the following packet

UUID: 12345678910245
Major: 22
Minor: 2

A device receiving this packet would understand it’s from the Coca-Cola Beacon (UUID) in the Target on 1st Street (Major) at the front of the store (Minor).

So now why and where we can use beacons?

For navigation- Beacons help guide navigators to their destinations. Types of navigational beacons include radar reflectors, radio beacons, sonic and visual signals. Visual beacons range from small, single-pile structures to large lighthouses or light stations and can be located on land or on water. Lighted beacons are called lights; unlighted beacons are called day-beacons.

For defensive communications- Classically, beacons were fires lit at well-known locations on hills or high places, used either as lighthouses for navigation at sea, or for signalling over land that enemy troops were approaching, in order to alert defenses. As signals, beacons are an ancient form of optical telegraphy, and were part of a relay league.


On vehicles or Shopping Malls--Vehicular beacons are rotating or flashing lights affixed to the top of a vehicle to attract the attention of surrounding vehicles and pedestrians. Emergency vehicles such as fire engines, ambulances, police cars, tow trucks, construction vehicles, and snow-removal vehicles carry beacon lights.And for malls to locate a particular shop in big mall.

Location-based mobile customer communication-

Apple explains iBeacon technology to consumers as the enabling technology for Apple devices to alert apps or websites (which the user has opted into) when someone approaches or leaves a location. In other words, retail or other venues that have beacons in place can detect where a customer is at any given moment. Then — and this is the key part, of course — the retailer or other business can push timely messages to that customer promoting products or providing other useful information. Say someone is walking past a retail store; if they’ve downloaded the retailer’s mobile app, the company can use beacon messages to capture their attention as they go by, enticing them to enter. Once inside, beacons can be used to make personalized offers, speed checkout processes and pretty much anything else the retailer can dream up.

Why is iBeacon a Big Deal? 

With an iBeacon network, any brand, retailer, app, or platform will be able to understand exactly where a customer is in the brick and mortar environment. This provides an opportunity to send customers highly contextual, hyper-local, meaningful messages and advertisements on their smartphones.

The typical scenario looks like this. A consumer carrying a smartphone walks into a store. Apps installed on a consumer’s smartphone listen for iBeacons. When an app hears an iBeacon, it communicates the relevant data (UUID, Major, Minor, Tx) to its server, which then triggers an action. This could be something as simple as a push message [“Welcome to Target! Check out Doritos on Aisle 3!”], and could include other things like targeted advertisements, special offers, and helpful reminders [“You’re out of Milk!”]. Other potential applications include mobile payments and shopper analytics and implementation outside of retail, at airports, concert venues, theme parks, and more. The potential is limitless.

This technology should bring about a paradigm shift in the way brands communicate with consumers. iBeacon provides a digital extension into the physical world. We’re excited to see where iBeacon technology goes in the next few years.