Android никогда не входит в didExitRegion

Я использую маяк estimote с библиотекой маяков Android. Я не могу получить didExitRegion. Все остальное работает нормально. Если приложение «видит» маяк, автоматически получает didEnterRegion, но если я нахожусь вне диапазона маяка, метод didExitRegion не вызывается. Тестирую на нексусе 5 с андроидом версии 5.1.1

Вот моя реализация библиотеки. Надеюсь, кто-нибудь может мне помочь.

public class MyApplicationName extends Application implements BootstrapNotifier {
private RegionBootstrap regionBootstrap;
private BackgroundPowerSaver backgroundPowerSaver;
private boolean haveDetectedBeaconsSinceBoot = false;
private HomePageActivity homePageActivity = null;

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

    BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
    beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
    Log.d("MyApplicationName", "Setting up background monitoring for beacons and power saving");
    Region region = new Region("B9407F30-F5F8-466E-AFF9-25556B57FE6D", null, null, null);
    regionBootstrap = new RegionBootstrap(this, region);
    backgroundPowerSaver = new BackgroundPowerSaver(this);
}

@Override
public void didEnterRegion(Region region) {

    Log.d("MyApplicationName", "did enter region");
    if (!haveDetectedBeaconsSinceBoot) {
        Log.d("MyApplicationName", "auto launching HomePageActivity");

        Intent intent = new Intent(this, HomePageActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
        haveDetectedBeaconsSinceBoot = true;
        //showNotification("Ciao", "ciaooo");
    }else {
        if(homePageActivity != null) {
            //showNotification("", "Welcome");
        }else {
            showNotification("", "Welcome");
        }
    }

    regionBootstrap.disable();
    Intent intent = new Intent(this, HomePageActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.startActivity(intent);
}

@Override
public void didExitRegion(Region region) {
    Log.d("MyApplicationName", "did exit region");
    showNotification("", "Goobbye");
}

@Override
public void didDetermineStateForRegion(int state, Region region) {
    Log.d("MyApplicationName", "See/not see beacon " + state);
}

private void showNotification(String title, String message) {
    Intent notifyIntent = new Intent(this, HomePageActivity.class);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivities(this, 0,
            new Intent[]{notifyIntent}, PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(this)
            .setPriority(Notification.PRIORITY_HIGH)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setStyle(new Notification.BigTextStyle().bigText(message))
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build();
    notification.defaults |= Notification.DEFAULT_SOUND;
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);
}

public void setMonitoringActivity(HomePageActivity activity) {
    this.homePageActivity = activity;
    Log.d("MyApplicationName", String.valueOf(activity));
}

}

public class HomePageActivity extends AppCompatActivity implements BeaconConsumer{


private BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);

private Collection<Beacon> beaconsPresent;
private String[] beaconsPresentMajorMinor;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_page);

    //beaconManager = BeaconManager.getInstanceForApplication(this);
    //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);
}


@Override
protected void onResume() {
    super.onResume();

    ((MyApplicationName) this.getApplicationContext()).setMonitoringActivity(this);
    if (beaconManager.isBound(this)) beaconManager.setBackgroundMode(false);
}

@Override
protected void onPause() {
    super.onPause();
    ((MyApplicationName) this.getApplicationContext()).setMonitoringActivity(null);
    if (beaconManager.isBound(this)) beaconManager.setBackgroundMode(true);
}

@Override
public void onDestroy() {
    super.onDestroy();
    beaconManager.unbind(this);
}

@Override
public void onBeaconServiceConnect() {

    beaconManager.addRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
            beaconsPresent = beacons;
            if(beacons.size() > 0) {
                for(Beacon b : beacons) {
                    System.out.println(b.getId2() + " " + b.getId3());
                    //getWelcomeMessage(b.getId2(), b.getId3());
                }
            }
        }
    });

    try {
        beaconManager.startRangingBeaconsInRegion(new Region("B9407F30-F5F8-466E-AFF9-25556B57FE6D", null, null, null));
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

}

Реализация androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />



<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:name=".MyApplicationName"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".HomePageActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


</application>


person Aleksandar Boshnakov    schedule 28.06.2017    source источник


Ответы (1)


Проблема заключается в следующей строке обратного вызова didEnterRegion:

regionBootstrap.disable();

Эта строка фактически отключит мониторинг региона, поэтому вы никогда не получите еще один обратный вызов входа или выхода. Простое решение — удалить эту строку.

person davidgyoung    schedule 28.06.2017
comment
Вы спасли мой день! - person Aleksandar Boshnakov; 28.06.2017