Я пытаюсь использовать библиотеку iBeacon вне контекста активности, чтобы написать ее эффективную реализацию, но у меня что-то не хватает, поскольку я не получаю желаемую функциональность.Использование библиотеки iBeacon для Android за пределами активности
Это, скорее всего, кажется, что служба не связана с моей недавно созданного класса .... и я не уверен, что я здесь отсутствует ...
Вот мой пользовательский класс:
public class BeaconUtils implements IBeaconConsumer, RangeNotifier, IBeaconDataNotifier {
private Context context;
protected static final String TAG = "BeaconUtils";
public BeaconUtils(Context context) {
this.context = context;
verifyBluetooth((Activity) context);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void verifyBluetooth(final Activity activity) {
try {
if (!IBeaconManager.getInstanceForApplication(activity).checkAvailability()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Bluetooth not enabled");
builder.setMessage("Please enable bluetooth in settings and restart this application.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
activity.finish();
//System.exit(0);
}
});
builder.show();
}
} catch (RuntimeException e) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Bluetooth LE not available");
builder.setMessage("Sorry, this device does not support Bluetooth LE.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
activity.finish();
//System.exit(0);
}
});
builder.show();
}
}
@Override
public void onIBeaconServiceConnect() {
Region region = new Region("MainActivityRanging", null, null, null);
try {
ZonizApplication.iBeaconManager.startMonitoringBeaconsInRegion(region);
ZonizApplication.iBeaconManager.setRangeNotifier(this);
ZonizApplication.iBeaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
ZonizApplication.iBeaconManager.setMonitorNotifier(new MonitorNotifier() {
@Override
public void didEnterRegion(Region region) {
//createNotification();
//Log.i(TAG, "I am in the range of an IBEACON: "+region.getProximityUuid());
//SyncServiceHelper.getInst().trySyncOffers(region.getProximityUuid());
}
@Override
public void didExitRegion(Region region) {
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(0);
}
@Override
public void didDetermineStateForRegion(int state, Region region) {
Log.i(TAG, "I have just switched from seeing/not seeing iBeacons: " + region.getProximityUuid());
createNotification();
}
});
}
@Override
public Context getApplicationContext() {
return this.context;
}
@Override
public void unbindService(ServiceConnection serviceConnection) {
ZonizApplication.iBeaconManager.unBind(this);
}
@Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
ZonizApplication.iBeaconManager.bind(this);
return true;
}
@Override
public void iBeaconDataUpdate(IBeacon iBeacon, IBeaconData iBeaconData, DataProviderException e) {
if (e != null) {
Log.d(TAG, "data fetch error:" + e);
}
if (iBeaconData != null) {
String displayString = iBeacon.getProximityUuid() + " " + iBeacon.getMajor() + " " + iBeacon.getMinor() + "\n" + "Welcome message:" + iBeaconData.get("welcomeMessage");
Log.d(TAG, displayString);
}
}
@Override
public void didRangeBeaconsInRegion(Collection<IBeacon> iBeacons, Region region) {
for (IBeacon iBeacon : iBeacons) {
iBeacon.requestData(this);
String displayString = iBeacon.getProximityUuid() + " " + iBeacon.getMajor() + " " + iBeacon.getMinor() + "\n";
Log.d(TAG, displayString);
}
}
public void createNotification() {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Build notification
// Actions are just fake
//if (currentUIID != null && !currentUIID.isEmpty()) {
Notification noti = new Notification.Builder(context)
.setContentTitle("New beacon in range")
.setContentText("You are currently in the range of a new beacon.").setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
noti.defaults |= Notification.DEFAULT_SOUND;
noti.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, noti);
//}
}
}
Я инстанцирование менеджера маяка в моем классе Application:
iBeaconManager = IBeaconManager.getInstanceForApplication(this);
и я связывание этого менеджера в своей деятельности в onCreate()
и onDestroy()
.
Что мне не хватает?
Я инстанцирование своего собственного класса в деятельности, как это:
private BeaconUtils beaconUtilities = new BeaconUtils(MainActivity.this);
Связующая часть:
beaconUtilities = new BeaconUtils(MainActivity.this);
ZonizApplication.iBeaconManager.bind(beaconUtilities);
Что вы получаете и то, что желаемая функциональность? –
Единственный журнал, который я получаю отсюда: 'Этот потребитель не связан. binding: ro.gebs.zonizbeacon.utils.BeaconUtils @ 41e3c040. Это похоже на то, что пользовательский класс не связан с активностью .... Я хотел бы видеть уведомление, поскольку я получал его, когда весь этот код был в моей деятельности класс –
System.exit (0); не должны использоваться на Android. – Kitesurfer