nearby_connections 1.0.2

nearby_connections #

An android flutter plugin for the Nearby Connections API Currently supports Bytes and Files.

pub package

Table of Content #

Setup #

Set Permissions #

Add these to AndroidManifest.xml

<!-- Required for Nearby Connections -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- Optional: only required for FILE payloads-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Since ACCESS_FINE_LOCATION and READ_EXTERNAL_STORAGE is considered to be dangerous system permissions, in addition to adding them to your manifest, you must request these permissions at runtime.

As a convinience this library provides methods to check and request location and external read/write permissions

// returns true/false asynchronously 
bool a = await Nearby().checkLocationPermissions()
// asks for permission only if its not given
Nearby().askLocationPermission()

// OPTIONAL: if you need to transfer files and rename it on device
Nearby().checkExternalStoragePermission()
// asks for READ + WRTIE EXTERNAL STORAGE permission only if its not given
Nearby().askExternalStoragePermission() 

Work Flow #

The work flow is similar to the Android Nearby Connections library

try {
    bool a = await Nearby().startAdvertising(
        userName,
        strategy,
        onConnectionInitiated: (String id,ConnectionInfo info) {
        // Called whenever a discoverer requests connection 
        },
        onConnectionResult: (String id,Status status) {
        // Called when connection is accepted/rejected
        },
        onDisconnected: (String id) {
        // Callled whenever a discoverer disconnects from advertiser
        },
    );
} catch (exception) {
    // platform exceptions like unable to start bluetooth or insufficient permissions 
}

Discover Advertisers #

try {
    bool a = await Nearby().startDiscovery(
        userName,
        strategy,
        onEndpointFound: (String id,String userName, String serviceId) {
            // called when an advertiser is found
        },
        onEndpointLost: (String id) {
            //called when an advertiser is lost (only if we weren't connected to it )
        },
    );
} catch (e) {
    // platform exceptions like unable to start bluetooth or insufficient permissions
}

Stopping Advertising and Discovery #

Nearby().stopAdvertising();
Nearby().stopDiscovery();
// endpoints already discovered will still be available to connect
// even after stopping discovery
// You should stop discovery once you have found the intended advertiser
// this will reduce chances for disconnection

Request Connection #

// to be called by discover whenever an endpoint is found
// callbacks are similar to those in startAdvertising method
try{ 
    Nearby().requestConnection(
        userName,
        id,
        onConnectionInitiated: (id, info) {
        },
        onConnectionResult: (id, status) {
        },
        onDisconnected: (id) {
        },
    );
}catch(exception){
    // called if request was invalid
}

Accept Connection #

Nearby().acceptConnection(
    id,
    onPayLoadRecieved: (endid,Uint8List bytes) {
        // called whenever a payload is recieved.
    },
    onPayloadTransferUpdate: (endid, payloadTransferUpdate) {
        // gives status of a payload
        // e.g success/failure/in_progress
        // bytes transferred and total bytes etc
    }
);

Sending Data #

Sending Bytes Payload #

Nearby().sendBytesPayload(endpointId, bytes_array);

// payloads are recieved by callback given to acceptConnection method.

Sending File Payload #

You need to send the File Payload and File Name seperately.

File is stored in DOWNLOAD_DIRECTORY and given a generic name So you would need to rename the file on receivers end.

//creates file with generic name (without extension) in Downloads Directory
//its your responsibility to rename the file properly
Nearby().sendFilePayload(endpointId, filePath);

//Send filename as well so that receiver can rename the file
Nearby().sendBytesPayload(endpointId,fileNameEncodedWithPayloadId);
//e.g send a string like "payloadId:FileExtensionOrName" as bytes

//payloads are recieved by callback given to acceptConnection method.

Every payload has an ID which is same for sender and receiver.

You can get the absolute FilePath from Payload in onPayloadReceived function

Checkout the Example in Repository for more details

1.0.2 #

  • Added payload cancellation and other assertions

1.0.1 #

  • Changed convinience methods for asking permissions(location+storage)
  • Updated example

1.0.0 #

  • Added support for Files (sendFilePayload)
  • Breaking Change (sendPayload method signature is changed)
  • Updated Example and Readme for file transfer

0.1.3+1 #

  • Update documentation and Readme

0.1.1 #

  • Fixed sendPayload future not completing bug

0.1.0 #

  • Added pub maintanence suggestions

0.0.2 #

  • Added dartdoc comments

0.0.1 #

  • Currently only bytes (max 32k array size) payload are supported
  • Analogous to NearbyConnection library in Android with similar callback names and all
  • Singleton pattern using factory constructor

example/README.md

nearby_connections_example #

Demonstrates how to use the nearby_connections plugin.

Checkout the Example repository for implementation of sending bytes and files.

Other examples using this is

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  nearby_connections: ^1.0.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:nearby_connections/nearby_connections.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
41
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
71
Learn more about scoring.

We analyzed this package on Aug 20, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.4.0
  • pana: 0.12.19
  • Flutter: 1.7.8+hotfix.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/src/nearby_connections.dart.

Run flutter format to format lib/src/nearby_connections.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.6 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test