我目前有一个应用程序设置可以使用 Azure 通知中心接收远程通知。 现在,我想扫描 iBeacons,看看附近是否有特定的 iBeacons,如果是,则不应向用户显示通知。但是,如果看不到信标,用户应该会收到此通知。
基本上,我希望信标能够抑制此应用程序的通知。
如何去做这件事?
最佳答案
基于the docs from Azure ,当远程通知到来时,您会收到如下回调:
public class MyHandler extends NotificationsHandler {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
@Override
public void onReceive(Context context, Bundle bundle) {
ctx = context;
String nhMessage = bundle.getString("message");
sendNotification(nhMessage);
if (MainActivity.isVisible) {
MainActivity.mainActivity.ToastNotify(nhMessage);
}
}
private void sendNotification(String msg) {
// put your notification code here
...
}
}
如果您想根据存在的信标来过滤通知,您可以将该逻辑添加到 onReceive 方法中,如下所示:
public void onReceive(Context context, Bundle bundle) {
if (!(MyApplication)this.getApplication()).isBeaconVisible()) {
// Suppress notification by returning early from method
return;
}
...
}
上面的 isBeaconVisible()
可以使用 Android Beacon 库在自定义 Android 应用程序类中实现,如下所示。您需要阅读更多有关如何设置该库才能实现此功能的信息。您还需要在 AndroidManifest.xml 中注册自定义 Application 类。
public class MyApplication extends Application implements BeaconConsumer, RangeNotifier {
public Collection<Beacon> mVisibleBeacons;
public void onCreate() {
super.onCreate();
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
// TODO: look up the proper I_BEACON_LAYOUT in a google search
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(I_BEACON_LAYOUT));
beaconManager.addRangeNotifier(this);
}
@Override
public void onBeaconServiceConnect() {
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
try {
beaconManager.startRangingBeaconsInRegion(new Region("all-beacons", null, null, null));
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
mVisibleBeacons = beacons;
}
public boolean isBeaconVisible() {
return mVisibleBeacons.size() > 0;
}
}
如果在最后一秒看到具有任何标识符的任何信标,则上述 isBeaconVisible()
逻辑将返回 true。但您可以根据您的要求更改它以使其更加复杂。
关于java - 收到远程通知后扫描 iBeacon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44922787/