搜尋套件、儲存庫與 APP 分類

套件詳情v4.3.0

nearby_connections

Android NearbyConnections API 的外掛程式。支援位元組與檔案。

Android
近 30 天下載
1.1萬
喜歡數
144
Pub 分數
160

安裝套件

flutter pub add nearby_connections

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

nearby_connections 套件提供 Flutter 與 Android Nearby Connections API 的整合,支援透過藍牙、Wi-Fi 及 NFC 在裝置之間進行點對點通訊。它支援原始位元組與檔案的傳輸,非常適合用於基於距離的本地資料分享應用。此外,該套件輕巧且專為 Android 設計,利用原生功能以實現可靠且低延遲的連線。對於需要直接設備間互動而無需網路依賴的協作應用、多人遊戲或檔案分享工具而言,極具實用性。

適用情境

  • 設備間的本地檔案共享
  • 即時多人遊戲同步
  • 群組設定中的離線資料交換
  • 設備間通訊的快速設定
  • 無雲端後端的協作應用功能

主要特色

  • 支援位元組和檔案傳輸
  • 使用 Android 原生 Nearby Connections API
  • 專為低延遲、短距離通訊優化
  • 適用於 Android 的簡單 Flutter 界面
  • 內建發現和連接管理

適合對象

  • 僅限 Android 的應用,需要本地設備連接
  • 需要快速離線資料傳輸的應用
  • 開發協作或社交功能的開發者
  • 專案避免依賴互聯網或雲端服務
  • 基於接近度互動的原型

使用建議

  • 僅限 Android 平台
  • 需要適當的權限(藍牙、位置)
  • 無 iOS 支援
  • 取決於裝置與附近連接的相容性
  • 後台操作可能受到 Android OS 的限制

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

nearby_connections

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

Transfer Data between multiple connected devices using fully offline peer to peer networking

pub package Stars Forks

Table of Content

Setup

Note regarding Location(GPS)

While using this, Location/GPS service must be turned on or devices may disconnect more often, some devices may disconnect immediately.

Set Permissions

Add these to your project's android/src/main/AndroidManifest.xml

<!-- Required for Nearby Connections -->
<uses-permission android:maxSdkVersion="31" android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:maxSdkVersion="31" android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:maxSdkVersion="30" android:name="android.permission.BLUETOOTH" />
<uses-permission android:maxSdkVersion="30" android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:maxSdkVersion="28" android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:minSdkVersion="29" android:maxSdkVersion="31" android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:minSdkVersion="31" android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:minSdkVersion="31" android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:minSdkVersion="31" android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:minSdkVersion="32" android:name="android.permission.NEARBY_WIFI_DEVICES" />
<!-- Optional: only required for FILE payloads -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Note: Android 12+ has introduced some new bluetooth permissions - BLUETOOTH_ADVERTISE, BLUETOOTH_CONNECT, BLUETOOTH_SCAN, which need to be handled as well. You may also need to set compileSdkVersion 32 in your build.gradle file.

Request Permissions

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

You can use:

// location permission
await Permission.location.isGranted         // Check Permission
await Permission.location.request()         // Ask

// Check Location Status
await Permission.location.serviceStatus.isEnabled;

// location enable dialog
await Location.instance.requestService()

// external storage permission
await Permission.storage.isGranted          // Check Permission
await Permission.storage.request()          // Ask

// Bluetooth permissions
bool granted = !(await Future.wait([        // Check Permissions
    Permission.bluetooth.isGranted,
    Permission.bluetoothAdvertise.isGranted,
    Permission.bluetoothConnect.isGranted,
    Permission.bluetoothScan.isGranted,
])).any((element) => false);
[                                           // Ask Permissions
    Permission.bluetooth,
    Permission.bluetoothAdvertise,
    Permission.bluetoothConnect,
    Permission.bluetoothScan
].request();

// Check Bluetooth Status
await Permission.bluetooth.serviceStatus.isEnabled;


// Android 12+
await Permission.nearbyWifiDevices.request()

Checkout the Example in Repository for more details.

NOTE

Location/GPS service must be turned on or devices may disconnect more often, some devices may disconnect immediately.

Work Flow

The work flow is similar to the Android Nearby Connections library

Advertise for connection
try {
    bool a = await Nearby().startAdvertising(
        userName,
        strategy, // https://developers.google.com/nearby/connections/strategies
        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
        },
        serviceId: "com.yourdomain.appname", // uniquely identifies your app
    );
} catch (exception) {
    // platform exceptions like unable to start bluetooth or insufficient permissions
}
Discover Advertisers
try {
    bool a = await Nearby().startDiscovery(
        userName,
        strategy, // https://developers.google.com/nearby/connections/strategies
        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 )
        },
        serviceId: "com.yourdomain.appname", // uniquely identifies your app
    );
} 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: (endpointId, payload) {
        // called whenever a payload is recieved.
    },
    onPayloadTransferUpdate: (endpointId, 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/.nearby/ and given a generic name. You need to copy the file to another directory of your choice.

//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 move and rename the file
Nearby().sendBytesPayload(endpointId,fileNameEncodedWithPayloadId);
//e.g send a string like "payloadId:FileExtensionOrFullName" 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 uri of the file from Payload in onPayloadReceived function. We have a convenience method to copy the file to a location you want-

// Convenience method to copy file using it's `uri`.
final newPath = '${await getExternalStorageDirectory}/$fileName';
await Nearby().copyFileAndDeleteOriginal(uri, newPath);

Checkout the Example in Repository for more details.

所屬分類

原始碼儲存庫

使用此套件的專案