从后台服务使用Beacon Library

时间:2014-10-06 23:03:43

标签: android ibeacon

我正在尝试在作为后台服务运行的应用中使用Android Beacon Library。我在服务启动时绑定了beaconManager。我解开onDestroy。然后,我想根据用户操作(on_duty / off_duty)

停止并开始测距

上个星期我尝试了几种组合,但我似乎无法在我停止之后正确地重新开始测距。在某些情况下,我从BeaconIntentProcessor获得以下内容:

"but ranging notifier is null, so we're dropping it."

调用停止和开始测距的正确方法是什么? 我是否应该能够基于(on_duty / off_duty)绑定和取消绑定服务 (我试过这个,但一直没能使它工作)

我的应用程序适用于个人现场使用信标在on_duty上定期检查不同位置,并希望在应用程序中禁用BLE而off_duty以节省电池。当应用程序处于off_duty模式时,我的应用程序仍然维护其他功能的后台服务。

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

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

-------------简单服务代码-------------

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());
                }


            }

    }

}

1 个答案:

答案 0 :(得分:0)

如果正确设置,应该没有问题。

我怀疑你得到了&#34;测距通知器是空的&#34;因为您没有在onBeaconServiceConnect()回调中设置范围通知程序。如果您在此方法中设置了测距通知程序,则可能需要发布代码,以便我们进一步提供帮助。