1

Suppose, Android app is detecting 3 beacons with in range with default UUID value. So, how can i set/change the name for each beacons in Anndroid (to identify each beacon)?

Appreciations for any suggestions... Thanks

4

3 回答 3

1
this is i got a solution to set different ids for different beacons. and also identifying differnet beacons and sending notifications to the user when app not in foreground.

I initially confused where to change Major and Minor values of beacons.

Simply, i installed Estimote Android app from Playstore 
here, 
1. Click on Beacons
2. Select one beacon and it displays one more detailed activity in that you can change Values (for me i changed Minor values for all beacon based on my requirement).

So, now Minor values for all beacons changed as per your requirement. After that find the below code

In this below code I am sending notification if App is in background or else i am dirctly updating statuses in Activity main class.

I changed Beacons values as 1,2,3,4. 


public class BeaconMyService extends Service {
    private static final String TAG = "BeaconMyService";
    private final Handler handler = new Handler();

    private BeaconManager beaconManager;

    private NotificationManager notificationManager;

    private static final Region ALL_ESTIMOTE_BEACONS_REGION = new Region("rid",
            null, null, null);

    private static final int NOTIFICATION_ID = 123;

    private Messenger messageHandler;
    Bundle extras;

    private String notifyMsg ="";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            extras = intent.getExtras();
            messageHandler = (Messenger) extras.get("MESSENGER");
        } catch (Exception e) {
            // TODO: handle exception
        }

        Log.e(TAG, "Called=============");
        if (beaconManager.isBluetoothEnabled()) {

            connectToService();
        }
        return Service.START_NOT_STICKY;

    }

    private void connectToService() {
        beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
            @Override
            public void onServiceReady() {
                try {
                    beaconManager.startRanging(ALL_ESTIMOTE_BEACONS_REGION);
                } catch (RemoteException e) {
                    Log.e("Myservice",
                            "Cannot start ranging, something terrible happened");
                    Log.e("", "Cannot start ranging", e);
                }
            }
        });
    }

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

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        beaconManager = new BeaconManager(this);

        beaconManager.setRangingListener(new BeaconManager.RangingListener() {

            @Override
            public void onBeaconsDiscovered(Region region,
                    final List<Beacon> beacons) {

                // Note that beacons reported here are already sorted by
                // estimated
                // distance between device and beacon.
                for (int index = 0; index < beacons.size(); index++) {
                    Beacon beacon = beacons.get(index);

                    if (beacon != null) {

                        if (beacons.size() > 0) {
                            if (Utils.computeAccuracy(beacons.get(0)) < 1.0) {
                                try {
                                    switch (beacons.get(0).getMinor()) {
                                    case 1:
                                        if (isAppInForeground(getApplicationContext())) {
                                            Message message = Message.obtain();
                                            message.arg1 = beacons.get(0)
                                                    .getMinor();
                                            try {
                                                messageHandler.send(message);
                                            } catch (RemoteException e) {
                                                e.printStackTrace();
                                            }

                                        } else {
                                            postNotification(beacons.get(0)
                                                    .getMinor()
                                                    + ". Welcome to Media Lab");
                                        }

                                        break;
                                    case 2:
                                        if (isAppInForeground(getApplicationContext())) {
                                            Message message = Message.obtain();
                                            message.arg1 = beacons.get(0)
                                                    .getMinor();
                                            try {
                                                messageHandler.send(message);
                                            } catch (RemoteException e) {
                                                e.printStackTrace();
                                            }

                                        } else {
                                            postNotification(beacons.get(0)
                                                    .getMinor()
                                                    + ". Welcome to Gaming Zone");
                                        }
                                        break;
                                    case 3:
                                        if (isAppInForeground(getApplicationContext())) {
                                            Message message = Message.obtain();
                                            message.arg1 = beacons.get(0)
                                                    .getMinor();
                                            try {
                                                messageHandler.send(message);
                                            } catch (RemoteException e) {
                                                e.printStackTrace();
                                            }

                                        } else {
                                            postNotification(beacons.get(0)
                                                    .getMinor()
                                                    + ". Welcome to eLearing Education");
                                        }
                                        break;
                                    case 4:
                                        if (isAppInForeground(getApplicationContext())) {
                                            Message message = Message.obtain();
                                            message.arg1 = beacons.get(0)
                                                    .getMinor();
                                            try {
                                                messageHandler.send(message);
                                            } catch (RemoteException e) {
                                                e.printStackTrace();
                                            }

                                        } else {
                                            postNotification(beacons.get(0)
                                                    .getMinor()
                                                    + ". Welcome to Retail Department");
                                        }
                                        break;
                                    default:
                                        break;
                                    }
                                } catch (Exception e) {
                                    // TODO: handle exception
                                }
                            }else{

                                if (isAppInForeground(getApplicationContext())) {
                                    Message message = Message.obtain();
                                    message.arg1 = 10;
                                    try {
                                        messageHandler.send(message);
                                    } catch (RemoteException e) {
                                        e.printStackTrace();
                                    }

                                }

//                              Utils.computeAccuracy(beacons.get(0))
                            }

                        }
                    }
                }

            }
        });

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    // ---helper method to determine if the app is in
    // the foreground---
    public static boolean isAppInForeground(Context context) {
        List<RunningTaskInfo> task = ((ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1);
        if (task.isEmpty()) {
            return false;
        }

        Log.e(TAG + "isAppInForeground-----",
                ""
                        + task.get(0).topActivity.getPackageName()
                                .equalsIgnoreCase(context.getPackageName()));

        return task.get(0).topActivity.getPackageName().equalsIgnoreCase(
                context.getPackageName());
    }

    private void postNotification(String msg) {
        if(!notifyMsg.equalsIgnoreCase(msg)){
            notifyMsg = msg;
            Intent notifyIntent = new Intent(BeaconMyService.this,
                    MainActivity.class);
            notifyIntent.putExtra("content", msg);

            notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivities(
                    BeaconMyService.this, 0, new Intent[] { notifyIntent },
                    PendingIntent.FLAG_UPDATE_CURRENT);

            Notification notification = new Notification.Builder(
                    BeaconMyService.this).setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("Monitoring Region").setContentText(msg)
                    .setAutoCancel(true).setContentIntent(pendingIntent).build();

            notification.defaults |= Notification.DEFAULT_SOUND;
            notification.defaults |= Notification.DEFAULT_LIGHTS;
            notificationManager.notify(NOTIFICATION_ID, notification);
        }

    }

}


Coming to Activity for updating status is this

package com.hcl.beacons_notification_ex;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

    static TextView tv_items;
    public static Handler messageHandler;

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

        tv_items = (TextView)findViewById(R.id.tv_items);
        messageHandler = new MessageHandler();
    }

    public static class MessageHandler extends Handler {
        @Override
        public void handleMessage(Message message) {
            int state = message.arg1;
            switch (state) {
            case 1:
                tv_items.setText("Welcome to Media Lab");
                break;
            case 2:
                tv_items.setText("Welcome to Gaming Zone");
                break;
            case 3:
                tv_items.setText("Welcome to eLearing Education");
                break;
            case 4:
                tv_items.setText("Welcome to Retail Department");
                break;
            default:
                tv_items.setText("Going far to Range");
                break;
            }
        }
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

        Intent i = new Intent(getApplicationContext(), BeaconMyService.class);
        if(isMyServiceRunning(BeaconMyService.class)){

        }else{
            i.putExtra("MESSENGER", new Messenger(messageHandler));
            startService(i);
//          startService(i);
        }

        try {
            if (getIntent().getExtras() != null) {
                tv_items.setText(""
                        + getIntent().getExtras().getString("content"));
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
于 2014-12-01T12:35:00.247 回答
1

信标不仅由 UUID 标识,还由它们的主要次要值来标识,而这整套(UUID + Major + Minor)是您可以区分它们的方法。

此外,这些值本质上是分层的,这允许您将一些结构放入信标部署中。考虑这个例子:

  • 整个博物馆:UUID = B9407F30-F5F8-466E-AFF9-25556B57FE6D
    • 北翼:少校 = 1
      • 图表 A:轻微 = 1
      • 图表 B:轻微 = 2
    • 南翼:少校 = 2

这样,当您的设备进入信标 B9407F30-F5F8-466E-AFF9-25556B57FE6D:1:2 的范围内时,只需查看它,您就会知道它位于北翼,附件 B。

于 2014-11-27T08:52:24.967 回答
0

首先你需要 estimote sdk 然后你可以创建一个像这样的 beaconDetection 服务

public class BeaconMyService extends Service
{
    private static final String TAG = "BeaconMyService";

    private final Handler handler = new Handler();

    private BeaconManager beaconManager;

    private static final Region ALL_ESTIMOTE_BEACONS_REGION = new Region("rid", null, null, null);

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        if (beaconManager.isBluetoothEnabled())
        {

            connectToService();
        }
        return Service.START_NOT_STICKY;

    }

    private void connectToService()
    {
        beaconManager.connect(new BeaconManager.ServiceReadyCallback()
        {
            @Override
            public void onServiceReady()
            {
                try
                {
                    beaconManager.startRanging(ALL_ESTIMOTE_BEACONS_REGION);
                }
                catch (RemoteException e)
                {
                    Log.e("Myservice", "Cannot start ranging, something terrible happened");
                    Log.e("", "Cannot start ranging", e);
                }
            }
        });
    }


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

        beaconManager = new BeaconManager(this);
        beaconManager.setRangingListener(new BeaconManager.RangingListener()
        {

            @Override
            public void onBeaconsDiscovered(Region region, final List<Beacon> beacons)
            {

                // Note that beacons reported here are already sorted by
                // estimated
                // distance between device and beacon.
                for (int index = 0; index < beacons.size(); index++)
                {
                    Beacon beacon = beacons.get(index);

                    if (beacon != null)
                    {
                        Log.v("Beacon MacAddress", beacon.getMacAddress() + "");
                        if (!Constants.BEACONSDETECTEDLIST.containsKey(beacon.getMacAddress()))
                        {//Constants.BEACONSDETECTEDLIST is your list of beacon mac addresses
                    //public static HashMap<String, Long> BEACONSDETECTEDLIST = new HashMap<String, Long>(); 
                        //to check if beacon is detected for the first time

                            if (Constants.BEACON1.equalsIgnoreCase(beacon.getMacAddress()))
                            {//Constants.BEACON1 is mac address of beacon 1 assigned in constants
                                Constants.BEACONSDETECTEDLIST.put(beacon.getMacAddress(), System.currentTimeMillis());
                                handler.postDelayed(beacon1Detection, 2000);
                            }
                            else if (Constants.BEACON2.equalsIgnoreCase(beacon.getMacAddress()))
                            {
                                Constants.BEACONSDETECTEDLIST.put(beacon.getMacAddress(), System.currentTimeMillis());
                                handler.postDelayed(beacon2Detection, 2000);
                            }
                        }
                        else
                        {/*Do Nothing*/
                        }

                    }
                }

            }
        });

    }

    private Runnable beacon1Detection = new Runnable()
    {
        public void run()
        {

            beacon1Info();
        }
    };

    private Runnable beacon2Detection = new Runnable()
    {
        public void run()
        {

            beacon2Info();
        }
    };

    private void beacon1Info()
    {
        Intent intent = new Intent(Constants.BEACON1BROADCAST_ACTION);
        sendBroadcast(intent);
    }//in Constants 
    //public static final String BEACON1BROADCAST_ACTION = "beacon1Action";



    private void beacon2Info()
    {
        Intent intent = new Intent(Constants.BEACON2BROADCAST_ACTION);
        sendBroadcast(intent);
    }// in Constants
    //public static final String BEACON2BROADCAST_ACTION = "beacon2Action";

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @Override
    public void onDestroy()
    {
        handler.removeCallbacks(beacon1Detection);
        handler.removeCallbacks(beacon2Detection);
        super.onDestroy();
    }
}

最后你需要一个 BeaconBroadcastReceiver 来接收服务中的广播并打开相应的 Activity

public class BeaconBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.BEACON1BROADCAST_ACTION)) {
                Intent intent2 = new Intent(context, Beacon1Layout.class);
                context.startActivity(intent2);

            } else if (intent.getAction().equals(Constants.BEACON2BROADCAST_ACTION)) {
                Intent intent2 = new Intent(context, Beacon2Layout.class);
                context.startActivity(intent2);

            }
        }

    }

希望这会对你有所帮助,祝你好运:)

于 2014-11-28T05:09:21.620 回答