Android 从后台服务使用Beacon库

Android 从后台服务使用Beacon库,android,ibeacon,Android,Ibeacon,我试图在一个作为后台服务运行的应用程序中使用Android Beacon库。我在服务开始时绑定beaconManager。我解开了锁。然后,我想根据用户在值班/下班时的操作停止和启动测距 上周我尝试了几种组合,但我似乎无法将其完全正确,在我停止后,测距将始终正确地重新启动。在某些情况下,我从BeaconIntentProcessor获得以下信息: "but ranging notifier is null, so we're dropping it." 调用停止和开始测距的正确方法是什么? 我

我试图在一个作为后台服务运行的应用程序中使用Android Beacon库。我在服务开始时绑定beaconManager。我解开了锁。然后,我想根据用户在值班/下班时的操作停止和启动测距

上周我尝试了几种组合,但我似乎无法将其完全正确,在我停止后,测距将始终正确地重新启动。在某些情况下,我从BeaconIntentProcessor获得以下信息:

"but ranging notifier is null, so we're dropping it."
调用停止和开始测距的正确方法是什么? 我是否应该不能基于值班/下班绑定和解除绑定服务 我已经尝试过了,但没有能够使它一直有效

我的应用程序是为个人在外地使用信标做定期检查,在不同的位置,而在值班和想禁用BLE应用程序,而下班,以节省电池。当应用程序处于下班模式时,我的应用程序仍然为其他功能维护后台服务

下面是启动顺序。不确定是否有问题-在最后,它继续循环通过相同的重新启动扫描序列

10-06 23:23:16.348: D/BeaconService(9203): No org.altbeacon.beacon.SimulatedScanData class exists.
10-06 23:23:16.348: I/BeaconService(9203): binding
10-06 23:23:16.408: I/BeaconService(9203): start monitoring received
10-06 23:23:16.408: D/BeaconService(9203): startMonitoring called
10-06 23:23:16.408: D/BeaconService(9203): Currently monitoring 1 regions.
10-06 23:23:16.408: D/BluetoothAdapter(9203): startLeScan(): null
10-06 23:23:16.468: D/BluetoothAdapter(9203): onClientRegistered() - status=0 clientIf=5
10-06 23:23:16.468: D/BeaconService(9203): Waiting to stop scan for another 1100 milliseconds
10-06 23:23:16.468: D/BeaconService(9203): Scan started
10-06 23:23:17.478: D/BeaconService(9203): Waiting to stop scan for another 99 milliseconds
10-06 23:23:17.568: D/BeaconService(9203): Done with scan cycle
10-06 23:23:17.598: D/BluetoothAdapter(9203): stopLeScan()

10-06 23:23:17.608: D/BeaconService(9203): Restarting scan.  Unique beacons seen last cycle: 0 Total beacon advertisement packets seen: 0
10-06 23:23:17.608: D/BluetoothAdapter(9203): startLeScan(): null
10-06 23:23:17.618: D/BluetoothAdapter(9203): onClientRegistered() - status=0 clientIf=5
10-06 23:23:17.618: D/BeaconService(9203): Waiting to stop scan for another 5000 milliseconds
10-06 23:23:17.618: D/BeaconService(9203): Scan started
10-06 23:23:18.618: D/BeaconService(9203): Waiting to stop scan for another 3999 milliseconds
10-06 23:23:18.978: D/BluetoothAdapter(9203): onScanResult() - Device=78:A5:04:5B:1A:F9 RSSI=-48
10-06 23:23:18.978: D/BeaconService(9203): got record
10-06 23:23:19.618: D/BeaconService(9203): Waiting to stop scan for another 2998 milliseconds
10-06 23:23:19.878: D/BluetoothAdapter(9203): onScanResult() - Device=78:A5:04:5B:1A:F9 RSSI=-48
10-06 23:23:19.878: D/BeaconService(9203): got record
10-06 23:23:20.618: D/BeaconService(9203): Waiting to stop scan for another 1998 milliseconds
10-06 23:23:20.788: D/BluetoothAdapter(9203): onScanResult() - Device=78:A5:04:5B:1A:F9 RSSI=-48
10-06 23:23:20.788: D/BeaconService(9203): got record
10-06 23:23:21.618: D/BeaconService(9203): Waiting to stop scan for another 997 milliseconds
10-06 23:23:21.698: D/BluetoothAdapter(9203): onScanResult() - Device=78:A5:04:5B:1A:F9 RSSI=-48
10-06 23:23:21.698: D/BeaconService(9203): got record
10-06 23:23:22.608: D/BluetoothAdapter(9203): onScanResult() - Device=78:A5:04:5B:1A:F9 RSSI=-48
10-06 23:23:22.608: D/BeaconService(9203): got record
10-06 23:23:22.618: D/BeaconService(9203): Done with scan cycle
10-06 23:23:22.618: D/BluetoothAdapter(9203): stopLeScan()

10-06 23:23:22.628: D/BeaconService(9203): Restarting scan.  Unique beacons seen last cycle: 0 Total beacon advertisement packets seen: 0
10-06 23:23:22.638: D/BluetoothAdapter(9203): startLeScan(): null
10-06 23:23:22.638: D/BluetoothAdapter(9203): onClientRegistered() - status=0 clientIf=5
10-06 23:23:22.648: D/BeaconService(9203): Waiting to stop scan for another 5000 milliseconds
10-06 23:23:22.648: D/BeaconService(9203): Scan started
10-06 23:23:23.658: D/BeaconService(9203): Waiting to stop scan for another 3993 milliseconds
10-06 23:23:24.418: D/BluetoothAdapter(9203): onScanResult() - Device=78:A5:04:5B:1A:F9 RSSI=-46
10-06 23:23:24.418: D/BeaconService(9203): got record
10-06 23:23:24.658: D/BeaconService(9203): Waiting to stop scan for another 2993 milliseconds
10-06 23:23:25.328: D/BluetoothAdapter(9203): onScanResult() - Device=78:A5:04:5B:1A:F9 RSSI=-47
10-06 23:23:25.328: D/BeaconService(9203): got record
10-06 23:23:25.658: D/BeaconService(9203): Waiting to stop scan for another 1992 milliseconds
10-06 23:23:26.228: D/BluetoothAdapter(9203): onScanResult() - Device=78:A5:04:5B:1A:F9 RSSI=-46
10-06 23:23:26.228: D/BeaconService(9203): got record
10-06 23:23:26.658: D/BeaconService(9203): Waiting to stop scan for another 991 milliseconds
10-06 23:23:27.648: D/BeaconService(9203): Done with scan cycle
10-06 23:23:27.648: D/BluetoothAdapter(9203): stopLeScan()
10-06 23:23:27.658: D/BeaconService(9203): Restarting scan.  Unique beacons seen last cycle: 0 Total beacon advertisement packets seen: 0
10-06 23:23:27.658: D/BluetoothAdapter(9203): startLeScan(): null
10-06 23:23:27.668: D/BluetoothAdapter(9203): onClientRegistered() - status=0 clientIf=5
10-06 23:23:27.678: D/BeaconService(9203): Waiting to stop scan for another 5000 milliseconds
10-06 23:23:27.678: D/BeaconService(9203): Scan started
10-06 23:23:28.678: D/BeaconService(9203): Waiting to stop scan for another 3999 milliseconds
-------下面是SimpleService代码-------

public class SimpleService extends Service implements BeaconConsumer
{
protected static final String TAG = "MyBeaconService";
private BeaconManager beaconManager;
RangingData rangingData = null;
Beacon beacon = null;
int  mapKey = 0;

ArrayList<String> sBeacons = new ArrayList<String>();
Hashtable<Integer, String> source = new Hashtable<Integer,String>();

final HashMap<Integer, String>  map = new HashMap(source);
final HashMap<Integer, String>  maptime = new HashMap(source);

String[] parts = null;


public class SimpleServiceBinder extends Binder
{
    public SimpleService getService()
    {

        return SimpleService.this;
    }
}




@Override
public IBinder onBind(Intent arg0) 
{
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate()
{
    super.onCreate();
    Log.i(TAG, "Service created ...");

    beaconManager = BeaconManager.getInstanceForApplication(getBaseContext());

 //   beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(this);

    // By default the AndroidBeaconLibrary will only find AltBeacons.  If you wish to make  it
    // find a different type of beacon, you must specify the byte layout for that beacon's
    // advertisement with a line like below.  The example shows how to find a beacon with the
    // same byte layout as AltBeacon but with a beaconTypeCode of 0xaabb
    //
    // beaconManager.getBeaconParsers().add(new BeaconParser().
    //        setBeaconLayout("m:2-3=aabb,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));

    beaconManager.getBeaconParsers().add(new BeaconParser().
            setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));


    beaconManager.bind(this);


    beaconManager.debug = true;
    beaconManager.setForegroundBetweenScanPeriod(1000);


}

@Override
public void onStart(Intent intent, int startId)
{
    Log.i(TAG,"onStart called");

    beaconManager.setBackgroundMode(false);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Log.i(TAG,"onStartCommand called");

    return START_STICKY; //START_REDELIVER_INTENT; 
}
@Override
public void onDestroy() 
{
    super.onDestroy();
    Log.i(TAG, "Service destroyed ...");
    //Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
     beaconManager.unbind(this);
}


    @Override
    public void onBeaconServiceConnect()
    {
        Log.i(TAG, "<<< onBeaconServiceConnect  >>>");

        beaconManager.setMonitorNotifier(new MonitorNotifier() 
        {


        @Override
        public void didEnterRegion(Region region)
        {

          Log.i(TAG, "onBeaconServiceConnect \ngetId1: "+region.getId1()+"\ngetId2: "+region.getId2()+"\ngetId3: "+region.getId3());
          Log.i(TAG, "**************-------------****************");


          logBeaconData(true);
        }

        @Override
        public void didExitRegion(Region region) 
        {
            //logToDisplay("Exit Region "+ region.getUniqueId(), true);
             Log.i(TAG, "********!!!!!!!!! didExitRegion !!!!!!!!!!*******");
             mapKey = 0;
             logBeaconData(false);
             try 
             {
                beaconManager.stopRangingBeaconsInRegion(new Region("sBeacon", null, null, null));
             } catch (RemoteException e) { e.printStackTrace();}

             Iterator<Integer> keySetIterator = map.keySet().iterator();

            while(keySetIterator.hasNext())
            {   
                Integer key = keySetIterator.next();

                Log.i(TAG, "****DELETE key: " + mapKey + " value: " + map.get(key));
                keySetIterator.remove();
                maptime.remove(key);

            }
            printtoscreen();


        }

        @Override
        public void didDetermineStateForRegion(int state, Region region) 
        {

             Log.i(TAG, "didDetermineStateForRegion \ngetId1: "+region.getId1()+"\ngetId2: "+region.getId2()+"\ngetId3: "+region.getId3());
        }


        });

        try {
            beaconManager.startMonitoringBeaconsInRegion(new Region("sBeacon", null, null, null));

        } catch (RemoteException e) {  Log.i(TAG, "RemoteException: "+e);   }
    }

    /**
     * 
     * @param iBeacon
     */
    private void logBeaconData(final boolean enter)
    {
        beaconManager.setRangeNotifier(new RangeNotifier() 
        {
        @Override 
        public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) 
        {

            if (beacons.size() > 0) 
            {

            //  sBeacons.clear();

                beacon = beacons.iterator().next();

                Log.i(TAG, " UUID: " + beacon.getId1());
                Log.i(TAG, " Major: " + beacon.getId2());
                Log.i(TAG, " Minor: " + beacon.getId3());
                Log.i(TAG, " RSSI: " + beacon.getRssi());
                Log.i(TAG, " Power: "+ beacon.getTxPower());
                Log.i(TAG, " Distance: "+ beacon.getDistance());



                    if (map.values().contains(beacon.getIdentifiers().toString()))
                    {
                   //   Log.i(TAG, "<<< Already there >>> "+beacon.getIdentifiers().toString());

                    }
                    else
                    {
                        mapKey = mapKey + 1;
                        map.put(mapKey, beacon.getIdentifiers().toString());
                        maptime.put(mapKey, ""+System.currentTimeMillis());

                    }

                    Iterator<Integer> keySetIterator = map.keySet().iterator();

                    final int seconds = 10;

                    while(keySetIterator.hasNext())
                    {   
                        Integer key = keySetIterator.next();


                        if (map.get(key).contains(beacon.getIdentifiers().toString()))
                        {
                            maptime.put(key, ""+System.currentTimeMillis());    
                        }

                        long diff = System.currentTimeMillis() - (Long.parseLong(maptime.get(key)));

                        int second = (int) ((diff / 1000) % 60);
                        Log.i(TAG, "key: " + key + " value: " + map.get(key)+" diff: "+second);

                        if(second >= seconds )
                        {
                            Log.i(TAG, "****DELETE key: " + mapKey + " value: " + map.get(key)+" diff: "+second);
                            keySetIterator.remove();    
                            maptime.remove(key);
                            //logToDisplay("\n** Beacon not longer reporting **"+ map.get(key), true); 
                        }
                        printtoscreen();

                    }

            }

        }

        });

        try
        {
            beaconManager.startRangingBeaconsInRegion(new Region("sBeacon", null, null, null));
            Log.i(TAG, "*** startRangingBeaconsInRegion ***");
        } catch (RemoteException e) {  Log.i(TAG, "RemoteException: "+e);   }

    }
    public void printtoscreen()
    {
        Iterator<Integer> keySetIterator = map.keySet().iterator();
         //   logToDisplay("", false);
            while(keySetIterator.hasNext())
            {   
                Integer key = keySetIterator.next();

                Log.i(TAG, "---------------------------------------------------");
                if (map.get(key) != null)
                {
                     parts = map.get(key).toString().substring(1, map.get(key).toString().length()-1).split("\\,");

                    Log.i(TAG, "---------------------------------------------------");
                    Log.i(TAG, "UUID:  " + parts[0]);
                    Log.i(TAG, "Major: " + parts[1]);
                    Log.i(TAG, "Minor: " + parts[2]);
                    Log.i(TAG, "RSSI: "+ beacon.getRssi());
                    Log.i(TAG, "Power: "+ beacon.getTxPower());
                    Log.i(TAG, "Distance: "+ beacon.getDistance());
                }


            }

    }

}

如果设置正确,做你想做的事情应该没有问题


我怀疑您得到的测距通知是空的,因为您没有在onBeaconServiceConnect回调中设置测距通知。如果您确实使用此方法设置了测距通知程序,您可能需要发布代码,以便我们进一步提供帮助。

我在OnBeacReconnect回调中设置了测距通知程序。当我重新启动服务时,我想我正在失去它。或者,如果我第二次把它弄得一团糟。我的代码通常在初始启动时工作。当我重新启动时,它停止工作。我是否应该总是取消绑定信标服务,然后在重新启动时绑定?我已经尝试过这种方法,然后将我上面发布的内容放到我的原始帖子中。你能发布你的代码吗?否则,我们只是在暗中摸索。@DavidYoung:我也得到了同样的结果。我用过这个代码@我已经更新了我原来的帖子,加入了上面的SimpleService代码。请为社区写问题;而不是个人和作者。