Code Monkey home page Code Monkey logo

flutter_beacon's Introduction

Flutter Beacon

Pub GitHub Build Coverage Status FOSSA Status codecov

Flutter plugin to work with iBeacons.

An hybrid iBeacon scanner and transmitter SDK for Flutter plugin. Supports Android API 18+ and iOS 8+.

Features:

  • Automatic permission management
  • Ranging iBeacons
  • Monitoring iBeacons
  • Transmit as iBeacon

Installation

Add to pubspec.yaml:

dependencies:
  flutter_beacon: latest

Setup specific for Android

For target SDK version 29+ (Android 10, 11) is necessary to add manually ACCESS_FINE_LOCATION

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

and if you want also background scanning:

<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

Setup specific for iOS

In order to use beacons related features, apps are required to ask the location permission. It's a two step process:

  1. Declare the permission the app requires in configuration files
  2. Request the permission to the user when app is running (the plugin can handle this automatically)

The needed permissions in iOS is when in use.

For more details about what you can do with each permission, see:
https://developer.apple.com/documentation/corelocation/choosing_the_authorization_level_for_location_services

Permission must be declared in ios/Runner/Info.plist:

<dict>
  <!-- When in use -->
  <key>NSLocationWhenInUseUsageDescription</key>
  <string>Reason why app needs location</string>
  <!-- Always -->
  <!-- for iOS 11 + -->
  <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>Reason why app needs location</string>
  <!-- for iOS 9/10 -->
  <key>NSLocationAlwaysUsageDescription</key>
  <string>Reason why app needs location</string>
  <!-- Bluetooth Privacy -->
  <!-- for iOS 13 + -->
  <key>NSBluetoothAlwaysUsageDescription</key>
  <string>Reason why app needs bluetooth</string>
</dict>

iOS Troubleshooting

  • Example code works properly only on physical device (bluetooth on simulator is disabled)
  • How to deploy flutter app on iOS device Instruction
  • If example code don't works on device (beacons not appear), please make sure that you have enabled
    Location and Bluetooth (Settings -> Flutter Beacon)

How-to

Ranging APIs are designed as reactive streams.

  • The first subscription to the stream will start the ranging

Initializing Library

try {
  // if you want to manage manual checking about the required permissions
  await flutterBeacon.initializeScanning;
  
  // or if you want to include automatic checking permission
  await flutterBeacon.initializeAndCheckScanning;
} on PlatformException catch(e) {
  // library failed to initialize, check code and message
}

Ranging beacons

final regions = <Region>[];

if (Platform.isIOS) {
  // iOS platform, at least set identifier and proximityUUID for region scanning
  regions.add(Region(
      identifier: 'Apple Airlocate',
      proximityUUID: 'E2C56DB5-DFFB-48D2-B060-D0F5A71096E0'));
} else {
  // android platform, it can ranging out of beacon that filter all of Proximity UUID
  regions.add(Region(identifier: 'com.beacon'));
}

// to start ranging beacons
_streamRanging = flutterBeacon.ranging(regions).listen((RangingResult result) {
  // result contains a region and list of beacons found
  // list can be empty if no matching beacons were found in range
});

// to stop ranging beacons
_streamRanging.cancel();

Monitoring beacons

final regions = <Region>[];

if (Platform.isIOS) {
  // iOS platform, at least set identifier and proximityUUID for region scanning
  regions.add(Region(
      identifier: 'Apple Airlocate',
      proximityUUID: 'E2C56DB5-DFFB-48D2-B060-D0F5A71096E0'));
} else {
  // Android platform, it can ranging out of beacon that filter all of Proximity UUID
  regions.add(Region(identifier: 'com.beacon'));
}

// to start monitoring beacons
_streamMonitoring = flutterBeacon.monitoring(regions).listen((MonitoringResult result) {
  // result contains a region, event type and event state
});

// to stop monitoring beacons
_streamMonitoring.cancel();

Under the hood

Author

Flutter Beacon plugin is developed by Eyro Labs. You can contact me at [email protected].

flutter_beacon's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flutter_beacon's Issues

Get all the beacons of all the region in IOS

I can't detect all the regions that i want
for example i have 2 regions and i want to find it then i start ranging

START RANGING=[{identifier=ibeacon, proximityUUID=99DF7F93-CB6E-4BB0-BE7F-335C373DC416}, {identifier=ibeacon, proximityUUID=B9BA7316-915A-449F-A8D3-512242D6A92D}]

but the ranging result shows beacons available on last region.

RangingResult{ "region": {"identifier":"ibeacon","proximityUUID":"b9ba7316-915a-449f-a8d3-512242d6a92d"}, "beacons": [{"proximityUUID":"B9BA7316-915A-449F-A8D3-512242D6A92D", "major":3,"minor":38,"rssi":-56,"accuracy":0.59,"proximity":"Proximity.near","txPower":-59,"macAddress":"AC:23:3F:2C:82:8E"}]} I/flutter (32741):

Please help me out i just want to scan multiple regions at a time so i can find beacons of different region.

I just want all the beacons of all proximityUUID available in area for IOS. Like in android just by
 entering
 `regions.add(Region(identifier: 'ibeacon'));`

Only indentifier not working for IOS

Hi,
I have used this same function for android and it works fine. But on IOS it seems not working. I never specified any UUID is cause I want to scan any UUID within the identifier: 'com.example.myDeviceRegion', ? How to achieve that in IOS ?

initScanBeacon() async {
await flutterBeacon.initializeScanning;
await checkAllRequirements();
if (!authorizationStatusOk ||
!locationServiceEnabled ||
!bluetoothEnabled) {
print('RETURNED, authorizationStatusOk=$authorizationStatusOk, '
'locationServiceEnabled=$locationServiceEnabled, '
'bluetoothEnabled=$bluetoothEnabled');
return;
}
final regions = [
Region(
identifier: 'com.example.myDeviceRegion',
),
];

if (_streamRanging != null) {
  if (_streamRanging.isPaused) {
    _streamRanging.resume();
    return;
  }
}

the example is not working

I've tried to run the example, but it not working on Android.

I am using the latest version of flutter ( v 1.7)

How to detect when beacon is out of range

Hello,
I use flutter_beacon for a connected tag for luggage project.
I attempt to push a local notification when the beacon device is out of range but it seems not work.

flutterBeacon.monitoring(regions).listen((result) async {
      //get gps coordinates
      Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
      if(position == null){
        position = await Geolocator().getLastKnownPosition(desiredAccuracy: LocationAccuracy.best);
      }

      if(result.monitoringEventType == MonitoringEventType.didEnterRegion) {
        //save to store with timestamp
        Storage().storeValue(
            "beacon_last_latitude", position.latitude.toString());
        Storage().storeValue(
            "beacon_last_longitude", position.longitude.toString());
        Storage().storeValue("beacon_last_timestamp",
            new DateTime.now().millisecondsSinceEpoch.toString());

        prefix0.log("BEACON FOUND: " + position.latitude.toString() + " - " +
            position.longitude.toString());
      } else if(result.monitoringEventType == MonitoringEventType.didExitRegion) {
        LocalNotification(BEACON_NOTIFICATION_CHANNEL, "Out of range", "Warning, your luggage is out of range.").send();
      }
});

In this case, i'm sure the local notification work but is never fired when i go away from my beacon. Do you have any idea to correct this issue ? Perhaps i don't understand the MonitoringEventType.

Thanks in advance,
Valentin

Background monitoring on Android

Hi!

I’ve tried to enable background monitoring on Android, as suggested on #40 adding that to the example app.

However, as soon as app goes to background, it stops receiving zone changes.

Do I need to add intent or something special to Android app for background beacon detection to work?

Thank you!

Ranging Beacons

Hello,

I'm new to flutter and I want to create a Beacon Scanning app, if I simply want to scan any nearby beacons and get their UUID do I use the ranging method?

Changing to default when you go away from Beacon

Hi,

I want to thank you for this great plugin.
I'm using it with great success, but I have a little problem:
I have a text that said "Unknow" while I'm away from any becon, and said some area name when I listen some beacon.
The problem was that when I go away after chnge the text from Unknow to the area name, it keep as that area until I find another beacon. I want it to chnge back to unknow if there are no beacons near.

I change my code and now it works as I want, when I go away the text come back to Unknow. My problem now is that when I'm near a becon, it dont keep the text even if I don´t move, it start to change from Unknow to Area Name.
This is my code, hope someone can tell me what I'm doing wrong:

    _streamRanging = flutterBeacon.ranging(regions).listen((result) {
      if (result != null && mounted) {

        _regionBeacons[result.region] = result.beacons;
        _beacons.clear();
        if (result.beacons.length == 0 && globals.Minor != 0){
          setState(() {
            globals.Minor = 0;
            globals.Ubicado = "Desconocida";
            globals.codArea = '0';
            globals.Sucio = false;
            globals.Limpio = false;
          });
        }
        _regionBeacons.values.forEach((list) {
          _beacons.addAll(list);
          if (_beacons[0].minor != globals.Minor){
            globals.Minor = _beacons[0].minor;
            BuscarArea(globals.Minor);
          }
          _beacons.sort(_compareParameters);
        });
      }
    });

Problem with 'regions'

Hello
I have a problem in the detection of beacons. Only one line makes the app to crash just after opening it.
This line is : regions.add(Region(identifier: 'com.beacon'));
Without it, the app open and runs on my device but it don't shows any beacons.

Here's the whole code :

import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_beacon/flutter_beacon.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  StreamSubscription<RangingResult> _streamRanging;
  final _regionBeacons = <Region, List<Beacon>>{};
  final _beacons = <Beacon>[];

  @override
  void initState() {
    super.initState();

    initBeacon();
  }

  initBeacon() async {
    try {
      await flutterBeacon.initializeScanning;
      print('Beacon scanner initialized');
    } on PlatformException catch (e) {
      print(e);
    }

    final regions = <Region>[];

    if (Platform.isIOS) {
      regions.add(Region(
          identifier: 'Apple Airlocate',
          proximityUUID: 'E2C56DB5-DFFB-48D2-B060-D0F5A71096E0'));
    } else {
      // android platform, it can ranging out of beacon that filter all of Proximity UUID
     regions.add(Region(identifier: 'com.beacon'));
    }

    flutterBeacon.monitoring(regions).listen((MonitoringResult result) {
      // result contains a region, event type and event state
    });

    _streamRanging = flutterBeacon.ranging(regions).listen((result) {
      result.beacons.forEach((b) {
        print(b.major);
        _beacons.sort(_compareParameters);
      });
    });
  }

  int _compareParameters(Beacon a, Beacon b) {
    int compare = a.proximityUUID.compareTo(b.proximityUUID);

    if (compare == 0) {
      compare = a.major.compareTo(b.major);
    }
    return compare;
  }

  @override
  void dispose() {
    if (_streamRanging != null) {
      _streamRanging.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Test détection balises'),
        ),
        body: _beacons == null
          ? Center(child: CircularProgressIndicator())
            : ListView(
          children: ListTile.divideTiles(
              context: context,
              tiles: _beacons.map((beacon) {
                return ListTile(
                  title: Text(beacon.proximityUUID),
                  subtitle: new Row(
                    mainAxisSize: MainAxisSize.max,
                    children: <Widget>[
                      Flexible(
                          child: Text(
                              'Major: ${beacon.major}\n',
                              style: TextStyle(fontSize: 13.0)),
                          flex: 1,
                          fit: FlexFit.tight),
                      Flexible(
                          child: Text(
                              'Accuracy: ${beacon.accuracy}m\nRSSI: ${beacon.rssi}',
                              style: TextStyle(fontSize: 13.0)),
                          flex: 2,
                          fit: FlexFit.tight)
                    ],
                  ),
                );
              })).toList(),
        ),
      ),
    );
  }
}

My phone is the Oneplus 6 under android 9.
What can I do to prevent this to happen ?

Plugin crashes on location permission request

In a specific scenario requesting location permission causes application to crash:

  1. Open app for the first so user is asked to enable location by the system.
  2. Call initializeScanning that also requests location permissions.
  3. Second request returns a result with empty permission arrays that causes method call handler to throw an exception (see below).
  4. When user grants/rejects permission then plugin catches also that result and attempts to post success/error on flutterResult instance (which is not set to null since the initialize method failed before reaching the code that clears it).
  5. Plugin crashes with java.lang.IllegalStateException: Reply already submitted.


This is the place in code that throws initially because of empty permissions and grantResults arrays:

public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  boolean locationServiceAllowed = false;
  String permission = permissions[0];
  ...
}

Which results in the following exception:

I/flutter (11033): Caught error: PlatformException(error, length=0; index=0, null)
I/flutter (11033): #0      StandardMethodCodec.decodeEnvelope 
package:flutter/…/services/message_codecs.dart:569
I/flutter (11033): #1      MethodChannel.invokeMethod 
package:flutter/…/services/platform_channel.dart:321
I/flutter (11033): <asynchronous suspension>
I/flutter (11033): #2      FlutterBeacon.initializeScanning
package:flutter_beacon/flutter_beacon.dart:54
I/flutter (11033): <asynchronous suspension>

doesn't work on ios 13

managed to run on iphone but it stuck on loading screen.
Bluetooth icon enabled only when 1st installed.

Missing files

When adding the plugin in pubspec.yaml it downloads without the authorization_status.dart and bluetooth_status.dart. Now it can be used only as a local plugin or in combination with other plugins that provide the necessary for location and bluetooth permissions. Any fix for the missing files soon?

Unable to detect Android devices

Hi, I used the plugin and the example code provided.
My iOS device is able to detect other iOS device. Android can detect iOS devices.
But both iOS and Android are not able to detect Android devices.

Any idea why?

Example App Unable to Install on iPhone

Hi, I wanted test out the library using the Example app on my iPhone, but while deploying the example via XCode after cloning the repo, seems like a directory dependency is not met:

ld: warning: directory not found for option '-L/Users/tree/flutter_beacon/example/build/ios/Debug-iphoneos/flutter_beacon'
ld: warning: directory not found for option '-L/Users/tree/flutter_beacon/example/build/ios/Debug-iphoneos/flutter_beacon'
ld: library not found for -lflutter_beacon
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thanks!

Unable to run example app

I have installed the plugin as specified on a new project on Android Studio and copied over the example app to my main.dart. Unfortunately I am getting the error below:

The name BluetoothState isn't a type so it cant be used as a type argument

at these lines:

final StreamController<BluetoothState> streamController = StreamController();
StreamSubscription<BluetoothState> _streamBluetooth;

Ranging/monitoring a beacon when app was terminated

Is it possible to monitor or rang a beacon when app work in background or terminated by the os? I can get monitoring events and ranging events when app is in foreground with this plugin. I tried to show a local notification for a right condition of beacons on background, but I could not.

flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.9.1+hotfix.2, on Mac OS X 10.14.6 18G95, locale en-TR)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 10.3)
[✓] Android Studio (version 3.4)
[✓] IntelliJ IDEA Ultimate Edition (version 2019.1.4)
[✓] VS Code (version 1.38.1)
[✓] Connected device (1 available)
No issues found!

Device

SM N950F • ce08171822449e08057e • android-arm64 • Android 9 (API 28)

Problem with Ranging Beacons after Initialization

Hello, I seem to have a problem where I can't range new regions with new uuids. It ranges only for the initial uuid I set. I have tried canceling the stream then adding a new region to the list then subscribing again however it does not work and it only reacts to the initial uuid. I have my code below. As you can see the ranging method starts the stream. Then in the onPressed property of the second button I first Cancel the stream then remove the first uuid region and then add a new region before starting the stream again.

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_beacon/flutter_beacon.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String result;
  StreamSubscription<RangingResult> _streamRanging;
  final regions = <Region>[];

 ** ranging() async {
    try {
      await flutterBeacon.initializeAndCheckScanning;
    } catch (e) {}

    if (Platform.isIOS) {
      regions.add(Region(
          identifier: 'Apple Airlocate',
          proximityUUID: 'E2C56DB5-DFFB-48D2-B060-D0F5A71096E0'));
    } else {
      regions.add(Region(
          identifier: null,
          proximityUUID: '87b7696c-3700-4fb6-b274-d089dfc44686'));
    }

    _streamRanging =
        flutterBeacon.ranging(regions).listen((RangingResult result) {
      print(result.region);
    });
  }**

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: Center(
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                width: 100,
                child: MaterialButton(
                  child: Text("Subscribe"),
                  color: Colors.blue,
                 ** onPressed: () {
                    ranging();
                  },**
                ),
              ),
              Container(
                width: 100,
                child: MaterialButton(
                  child: Text("Cancel"),
                  color: Colors.blue,
               **   onPressed: () {
                    _streamRanging.cancel();
                    regions.removeLast();
                    regions.add(Region(
                        identifier: null,
                        proximityUUID: '98173b7d-2444-424a-bed9-7acf4bf97a50'));
                    _streamRanging = flutterBeacon
                        .ranging(regions)
                        .listen((RangingResult result) {
                      print(result.region);
                    });
                  },**
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Accuracy Calculation

Hello,

Thank you very much for your work.

Could you make two changes in your code?

The first to have the value RSSI of type double with precision of 2 decimals.

The second to change the distance calculation (accuracy) http://stackoverflow.com/a/20434019

double calculateAccuracy(int txPower, double rssi){
    if(rssi == 0)
      return -1.0;
    double ratio = rssi*1.0/txPower;
    if(ratio < 1.0)
      return pow(ratio, 10);
    else {
      double accuracy = (0.89976)*pow(ratio,7.7095) + 0.111;
      return num.parse(accuracy.toStringAsFixed(2));
    }
  }

Scanning frequency

Hi,

Is possible to modify de scanning frequency? the beacons that i'm using can advertise with faster intervals (100ms, 200ms, and so on). Is posible to modify the frequency at which the app does the scan so i can get more measurements?

Thank you!

Put major in a variable

Hi, I try to create a variable like this final _major = result.beacons[].major but I don't understand what is an index of desired beacon.
I try this line final _major = result.beacons[].major
I try add this line with other variable
class _MyAppState extends State
{
StreamSubscription _streamRanging;
final _beacons = [];
final _major = result.beacons[].major;
....
} but there are an issue with result which does not existe
I try add my line in
_streamRanging = flutterBeacon.ranging(regions).listen
((result)
{
result.beacons.forEach
((b)
{
final _major = result.beacons[].major;
print(b.major);
_beacons.sort(_compareParameters);
monid =b.major;
print('monid=');
print(monid);
return b.major;
}
);
}
); with this code the issue is "The argument type 'List' can't be assigned to the parameter type 'int'"
my goal it's take the major and put it in a variable. But I am a beginner in flutter , can you help please

Get Mac Address iOS

Hi,

I have managed to differentiate beacons from one another with the same UUID on Android with Mac Address, but on iOS it can't get a Mac Address beacon, is there another method to distinguish beacons with the same UUID, Thank you very much for your great work.

Versions problem

Hi, I was working with flutter_beacon: ^0.2.4 without any problem.

I change in my Android/build.gradle file the following:
change kotlin_version from 1.2.71 to 1.3.0
change gradle version from 3.2.1 to 3.3.2

now it gives me this message:

Running Gradle task 'assembleDebug'...
Note: D:\src\flutter.pub-cache\hosted\pub.dartlang.org\flutter_beacon-0.2.4\android\src\main\java\com\flutterbeacon\FlutterBeaconPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

It is still working but I'm a little concern about this message

Returning to the principal widget it don´t listen any more

Hi,

I made a flutter app, it listen to the beacon and show me where I am. I add a couple of buttons to list all the areas and another funcionality. When I change the widget using Navigator.pushReplacementNamed and then I go back to my principal widget using the same function, the app stop listening the beacon.

I was trying to find out why, and I think the problem is in this call

await flutterBeacon.initializeScanning

because the first time when I call it the app leave me this output:

I/BeaconManager(21986): BeaconManager started up on pid 21986 named 'cl.teknopartner.clean_control' for application package 'cl.teknopartner.clean_control'. isMainProcess=true
D/BeaconParser(21986): Parsing beacon layout: m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25

but when I come back to this widget and make the same call, it doesn´t show me anything of this. I'm not sure if I have problem in the way I´m using this pluggin in my app :(

Example project Accuracy/RSSI values can't be acquired on iOS

When I run the example project on iOS devices I can't see the Accuracy or RSSI values of the beacons that have been found. Accuracy is always -1.0. The example runs without any problem on a Galaxy S6 Android device (RSSI can be read correctly) but not on an iPhone 6 Plus or a 6th generation iPad. Any idea what might be causing this or can these values be reached from iOS? I've added a screenshot from the iPad, Thanking you in advance.

Edit: I am using iBeacons which are very similar to the link here.

IMG_A8456207F40A-1

Background monitor in android

Hi, i want get ibeacon uuid , major and minor when app killed.
Its work on ios so good and no problem there.
But, in android, app can not get data in monitor region method.
I tried to reopen app or resume ranging stream when monitor received data, but there is no data.

Any Help?

problems while ranging in ios and huawei devices

im using this plugin on my project to detect ble device and its worked with me in all type of devices except huawei devices and some of ios , before that ios and huewai was work on it but today i open it to test and, that what i got :

════════ Exception caught by services library ══════════════════════════════════
The following PlatformException was thrown while activating platform stream on channel flutter_beacon_event:
PlatformException(error, Unable to parse Identifier., null)

When the exception was thrown, this was the stack
#0      StandardMethodCodec.decodeEnvelope 
package:flutter/…/services/message_codecs.dart:569
#1      MethodChannel._invokeMethod 
package:flutter/…/services/platform_channel.dart:156
<asynchronous suspension>
#2      MethodChannel.invokeMethod 
package:flutter/…/services/platform_channel.dart:329
#3      EventChannel.receiveBroadcastStream.<anonymous closure> 
package:flutter/…/services/platform_channel.dart:519
...
════════════════════════════════════════════════════════════════════════════════

please help i dont know whats going on everythings in there place

many thanks

Multiple Beacon Detection

HI!

Firstly thanks for the great Plugin! I have had some pretty good success with it and its a really good solution!

Just one problem that I have had, I am trying to detect multiple beacons at once, I thought this would be fairly easy because in order to range the beacons you have to accept a list, however for some reason the region only accepts the first list item.

I have figured out that when i listen to the stream like in the line beaconStream.listen(print); it does output all the beacons, However then it outputs two beacons and a duplicate beacon.

The reason I would like to do this, is i would like to output the beacons to a streambuilder widget and build a list of the beacons.

Here is my code:

  Future<List<Region>> fetchBeacons() async {
    List<Region> regions = [];
    regions = [
      Region(
          proximityUUID: 'AFC0FF69-3ACB-4A99-9F6A-2A4B6F786619',
          identifier: 'T-Shirt Beacon',
          major: 1,
          minor: 1),
      Region(
          proximityUUID: '705DAEE5-56BC-415A-839B-4AE00FC29946',
          identifier: 'Test',
          major: 1,
          minor: 1),
    ];
    return regions;
  }

  Future<Stream<RangingResult>> scanBeacons() async {
    await flutterBeacon.initializeScanning;
    List<Region> regions = await fetchBeacons();
    Stream<RangingResult> beaconStream = flutterBeacon.ranging(regions);
    beaconStream.listen(print);
    return beaconStream;
  }Ï

And this is the stream response to the console from the streambuilder:

RangingResult{"region": {"identifier":"T-Shirt Beacon","proximityUUID":"AFC0FF69-3ACB-4A99-9F6A-2A4B6F786619","major":1,"minor":1}, "beacons": []}

And from the beaconStream.listen

flutter: RangingResult{"region": {"identifier":"Test","proximityUUID":"705DAEE5-56BC-415A-839B-4AE00FC29946","major":1,"minor":1}, "beacons": []}
flutter: RangingResult{"region": {"identifier":"T-Shirt Beacon","proximityUUID":"AFC0FF69-3ACB-4A99-9F6A-2A4B6F786619","major":1,"minor":1}, "beacons": []}
flutter: RangingResult{"region": {"identifier":"T-Shirt Beacon","proximityUUID":"AFC0FF69-3ACB-4A99-9F6A-2A4B6F786619","major":1,"minor":1}, "beacons": []}

Stop scanning

Hi,
I couldn't find on FlutterBeacon.dart any method to stop scanning even though on native implementations I found these methods. Is this intended or work on progress?

Also, it would be a nice improvement to get the LocationService'authorizationStatus for a better handling of states.

Best regards!😃

Serial number and battery

Hi,

There are any way to have the serial number of a beacon?

There are any way to know how much battery does it have?

I want to send an alert when some beacon is lower in battery.

thanks in advance

Catch with ios13

flutterBeacon.initializeScanning catch and terminate with ios13. When i by pass this process app can work, But beacon.ranging don't work.

how can i fix it?

Thank you.

Ranging in background

Hi @alann-maulana, thanks for the library to make iBeacon detection easy and so our life :)

I'm trying to range the iBeacon as:

class _MyHomePageState extends State<MyHomePage> {

 @override
  void initState() {
      super.initState();
     ...
     initializeScanning();
 }

 void initializeScanning() async {
    try {
      await flutterBeacon.initializeAndCheckScanning;
      startRanging();
    } catch(e) {
      print(e);
    }
  }
 
 void startRanging()
 {
   final regions = <Region>[
      Region(identifier: Platform.isIOS ? this.identifier : null, 
                  proximityUUID: this.uuid)
  ];

  _streamRanging = flutterBeacon.ranging(regions).listen((RangingResult result) { 
      //Do some calculations for distance on detected beacon
      //Display the result in ListView
      //Fire local notification
  });
 }

}

I've tested this with 2 android devices. Its working fine when the app is in foreground, but I'm not getting notification when app is in background.

I was reading other issues and found your line: "some devices need to add some lines to enable background monitoring directly on Java/Kotlin code within Android project" from #45.

I would like to know those lines. Also, could you please help with the example on how can we detect iBeacon in both background and when app terminated for android. Once I achieve this for android, I'll head in for iOS later.

Beacon Info when Monitoring

Would be useful to obtain the beacon Info when I use monitoring feature.
In the result I've

  • type
  • status
  • region (the region identifier and proximityUUID)

I need also major and minor info to understand What beacon is calling me (Like in Ranging feature).

use only major

Hi, I would like take the major value dans add it at the end of an http link but a not arrive because I don't know how I should to take the major from the Beacon list.
I try to use this line code : final _major=Beacon.fromJson('major'); and I have an issue like 'String' not a subtype of 'int' or 'index'.

Compilation fails with Flutter 1.1.8 and androidx

Compilation fails after upgrading flutter and migrating to androidx. Probably related to

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v1.1.8, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Android Studio (version 3.3)
[!] VS Code (version 1.27.2)
    ✗ Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[✓] Connected device (1 available)

! Doctor found issues in 1 category.

Error:

Note: /home/xxx/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-3.0.0/android/src/main/java/io/flutter/plugins/firebasemessaging/FlutterFirebaseInstanceIDService.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
/home/xxx/.pub-cache/hosted/pub.dartlang.org/flutter_beacon-0.1.1/android/src/main/java/com/flutterbeacon/FlutterBeaconPlugin.java:14: error: cannot find symbol
import android.support.v4.app.ActivityCompat;
                             ^
  symbol:   class ActivityCompat
  location: package android.support.v4.app
/home/xxx/.pub-cache/hosted/pub.dartlang.org/flutter_beacon-0.1.1/android/src/main/java/com/flutterbeacon/FlutterBeaconPlugin.java:15: error: package android.support.v4.content does not exist
import android.support.v4.content.ContextCompat;
                                 ^
/home/xxx/.pub-cache/hosted/pub.dartlang.org/flutter_beacon-0.1.1/android/src/main/java/com/flutterbeacon/FlutterBeaconPlugin.java:113: error: cannot find symbol
        ActivityCompat.requestPermissions(registrar.activity(), new String[]{
        ^
  symbol:   variable ActivityCompat
  location: class FlutterBeaconPlugin
/home/xxx/.pub-cache/hosted/pub.dartlang.org/flutter_beacon-0.1.1/android/src/main/java/com/flutterbeacon/FlutterBeaconPlugin.java:122: error: cannot find symbol
      return ContextCompat.checkSelfPermission(registrar.activity(),
             ^
  symbol:   variable ContextCompat
  location: class FlutterBeaconPlugin
/home/xxx/.pub-cache/hosted/pub.dartlang.org/flutter_beacon-0.1.1/android/src/main/java/com/flutterbeacon/FlutterBeaconPlugin.java:229: error: cannot find symbol
      if (!ActivityCompat.shouldShowRequestPermissionRationale(registrar.activity(), permission)) {
           ^
  symbol:   variable ActivityCompat
  location: class FlutterBeaconPlugin
/home/xxx/.pub-cache/hosted/pub.dartlang.org/flutter_beacon-0.1.1/android/src/main/java/com/flutterbeacon/FlutterBeaconPlugin.java:256: error: cannot find symbol
        ActivityCompat.requestPermissions(registrar.activity(), new String[]{
        ^
  symbol:   variable ActivityCompat
  location: class FlutterBeaconPlugin
Note: /home/xxx/.pub-cache/hosted/pub.dartlang.org/flutter_beacon-0.1.1/android/src/main/java/com/flutterbeacon/FlutterBeaconPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':flutter_beacon:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 12s
Finished with error: Gradle task assembleDebug failed with exit code 1

build.gradle:

android {
    compileSdkVersion 28
    lintOptions {
        disable 'InvalidPackage'
    }
    defaultConfig {
        applicationId "cz.myapp"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

Not working when ranging beacon

Using the function Ranging beacon, I got the error like this: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/content/LocalBroadcastManager. Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available. I dont know how to fix this issue. Is there anyone know how to solve this problem ?

Cannot initialize flutterBeacon

I am not able to initialise flutterBeacon after updating to latest version 0.3.0. Here is my log:
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'int' is not a subtype of type 'bool' #0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:13) <asynchronous suspension> #1 FlutterBeacon.initializeScanning (package:flutter_beacon/flutter_beacon.dart:65:33)

I have only tested this in IOS so, I am not sure with android. I get this error with lutterBeacon.initializeScanning which was working fine with previous versions.

Unhandled Exception: type 'int' is not a subtype of type 'bool'

Hi, I'm getting this error message when starting the example application.

My Device:

  • flutter_beacon 0.3.0
  • iPhone X on iOS 13.3
  • Flutter 1.12.13+hotfix.5 / Dart 2.7.0
  • Beacon Sensoro 4AA Pro

The example application didn't find the beacon, I'm migrating my native application to flutter, so I know the beacon is working properly.

flutter: Listening to bluetooth state
flutter: AppLifecycleState = AppLifecycleState.resumed
flutter: AppLifecycleState = AppLifecycleState.resumed
flutter: BluetoothState = Instance of 'BluetoothState'
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'int' is not a subtype of type 'bool'
#0      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:13)
<asynchronous suspension>
#1      FlutterBeacon.initializeScanning (package:flutter_beacon/flutter_beacon.dart:65:33)
#2      _MyAppState.initScanBeacon (package:flutter_app/beacon.dart:75:25)
#3      _MyAppState.listeningState.<anonymous closure> (package:flutter_app/beacon.dart:47:11)
#4      _rootRunUnary (dart:async/zone.dart:1134:38)
#5      _CustomZone.runUnary (dart:async/zone.dart:1031:19)
#6      _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
#7      _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
#8      _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
#9      _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:134:11)
#10     _MapStream._handleData (dart:async/stream_pipe.dart:234:10)
#11     _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:166:13)
#12     _rootRunUnary (dart:async/zone.dart:1134:38)
#13     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
#14     _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
#15     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
#16     _DelayedData.perform (dart:async/stream_impl.dart:593:14)
#17     _StreamImplEvents.handleNext (dart:async/stream_impl.dart:709:11)
#18     _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:669:7)
#19     _rootRun (dart:async/zone.dart:1122:38)
#20     _CustomZone.run (dart:async/zone.dart:1023:19)
#21     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#22     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#23     _rootRun (dart:async/zone.dart:1126:13)
#24     _CustomZone.run (dart:async/zone.dart:1023:19)
#25     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#26     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#27     _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
#28     _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)

are this plugin support beacon accelerometer sensor ??

hello everyone after more than 3 months using this plugin and I thanks all who has develop it , I need to get the accelerometer xyz data are that possible and if i have an sdk with native how can I handle that with this plugin ....

thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.