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...



No comments: