Не удалось найти ни одного маяка с альтбэком андроид - PullRequest
0 голосов
/ 29 августа 2018

Я использую altbeacon для Android и не могу обнаружить мой маяк. Я пробовал https://github.com/AltBeacon/android-beacon-library-reference пример кода, но не могу определить маяк. Вот мой код:

открытый класс BeaconApplication расширяет приложение, реализует BootstrapNotifier {

private Region region;
private RegionBootstrap regionBootstrap;
private BeaconManager beaconManager;

@Override
public void onCreate() {
    super.onCreate();
    beaconManager = BeaconManager.getInstanceForApplication(this);
    beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=beac,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.setBackgroundScanPeriod(5000);
    beaconManager.setBackgroundBetweenScanPeriod(10000);
    region = new Region("backgroundRegion",
            Identifier.parse("EBEFD083-70A2-47C8-9837-E7B5634DF524"), null, null);
    regionBootstrap = new RegionBootstrap(this, region);
    Log.i("selfBeacon", "Bootstrap created");
}

@Override
public void didEnterRegion(Region region) {
    Log.i("selfBeacon", "Bootstrap didEnterRegion");
    regionBootstrap.disable();
    Intent intent = new Intent(this, SelfBeaconService.class);
    if (Build.VERSION.SDK_INT >= 26) {
        startForegroundService(intent);
    } else {
        startService(intent);
    }
    Log.i("selfBeacon", "Service start commanded");
}

@Override
public void didExitRegion(Region region) {

}

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

}

public void resumeScanning () {
    beaconManager.setBackgroundScanPeriod(5000);
    beaconManager.setBackgroundBetweenScanPeriod(10000);
    regionBootstrap = new RegionBootstrap(this, region);
    Log.i("selfBeacon", "scanning resumed");
}

}

открытый класс SelfBeaconService расширяет службу, реализует BeaconConsumer {

private BeaconManager beaconManager;
private Region region;
private int noBeaconDetectedCount = 0;

@Override
public void onCreate() {
    super.onCreate();
    Log.i("selfBeaconService", "onCreate");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("selfBeaconService", "onStartCommand");
    broadcastSystemLog("Beacon Service onCreate triggered.");
    beaconManager = BeaconManager.getInstanceForApplication(this);
    beaconManager.setEnableScheduledScanJobs(false); //Stop scanning
    beaconManager.setForegroundScanPeriod(2000);
    beaconManager.setForegroundBetweenScanPeriod(2000);
    beaconManager.bind(this);
    region = new Region("foreground region",
            Identifier.parse("EBEFD083-70A2-47C8-9837-E7B5634DF524"), null, null);

    startForeground();

    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onBeaconServiceConnect() {
    Log.i("selfBeaconService", "onBeaconServiceConnect");
    broadcastSystemLog("onBeaconServiceConnect triggered.");
    beaconManager.addRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
            if (collection.size() > 0) {
                noBeaconDetectedCount = 0;
                double closestDistance = -1;
                for (Beacon each : collection) {
                    if (closestDistance == -1) {
                        closestDistance = each.getDistance();
                    } else if (each.getDistance() < closestDistance) {
                        closestDistance = each.getDistance();
                    }
                }
                Log.i("selfBeaconService", "didRangeBeaconsInRegion, the closest beacon is about " +
                        closestDistance + " meters away.");
                broadcastToActivity("The closest beacon is about " +
                        closestDistance + " meters away.");
            } else {
                noBeaconDetectedCount++;
                broadcastToActivity("No beacon has been detected for " + noBeaconDetectedCount + " times");
                if (noBeaconDetectedCount > 10) { //10*(2000ms+2000ms) = 40 seconds
                    stopForeground(true);
                    terminate();
                }
            }
        }
    });

    try {
        beaconManager.startRangingBeaconsInRegion(region);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

@Override
public void onDestroy() {
    Log.i("selfBeacon", "onDestroy");
    broadcastSystemLog("BeaconService onDestroy triggered.");
    super.onDestroy();
}

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

private void broadcastToActivity (String message) {
    Intent intent = new Intent();
    intent.setAction("beaconBroadcast");
    intent.putExtra("beaconService", message);
    sendBroadcast(intent);
}

private void broadcastSystemLog (String message) {
    Intent intent = new Intent();
    intent.setAction("beaconBroadcast");
    intent.putExtra("beaconServiceLog", message);
    sendBroadcast(intent);
}

private void startForeground () {
    NotificationCompat.Builder notificationBuilder = null;
    Notification notification = null;
    if (Build.VERSION.SDK_INT >= 26) {
        notificationBuilder = new NotificationCompat.Builder(this, "rangingService")
                .setContentTitle("Active Scanning")
                .setContentText("App is scanning for nearby beacons");
        notification = notificationBuilder.build();
    } else {
        notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("Active Scanning")
                .setContentText("App is scanning for nearby beacons");
        notification = notificationBuilder.build();
    }
    startForeground(1234, notification);
}

private void terminate () {
    try {
        beaconManager.stopRangingBeaconsInRegion(region);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
    beaconManager.removeAllRangeNotifiers();
    beaconManager.unbind(this);
    beaconManager.setEnableScheduledScanJobs(true);
    ((BeaconApplication)getApplication()).resumeScanning();
    stopSelf();
    Log.i("selfBeaconService", "service stopped");
    broadcastSystemLog("BeaconSevice stopped.");
}

}

1 Ответ

0 голосов
/ 30 августа 2018

Несколько вещей для проверки:

  1. Убедитесь, что вы добавили код для динамического запроса разрешения местоположения во время выполнения. См. здесь , чтобы узнать, как это сделать.
  2. После добавления вышеупомянутого убедитесь, что это разрешение было получено правильно. Идти к. Настройки-> Приложения -> {имя вашего приложения} -> Разрешения на просмотр
  3. Убедитесь, что на вашем телефоне включены Bluetooth и Location.
  4. Если вы проверили все вышеперечисленное, но оно все еще не работает, попробуйте стандартный маяковый детектор, например BeaconScope . Если он не обнаружит, возможно, проблема в вашем телефоне или в маяке.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...