패키지, 저장소 및 앱 카테고리 검색

GitHub 저장소mannprerak2/nearby_connections

nearby_connections

바이트 및 파일을 오프라인으로 공유하기 위한 플러터 플러그인(안드로이드)(Android Nearby Connections API 기반)

nearby_connections 프로젝트 이미지
스타
101
포크
35
최근 푸시(UTC)
2025. 2. 19.
프로젝트 상태
활성

원본 README

아래는 영문 원문 스냅샷입니다. 최신 내용은 GitHub에서 확인하세요.

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.

Prerak Mann GitHub avatar
GitHub 작성자

Prerak Mann ↗

Software Engineer | Java | Python | GSoC'20 @dart-lang | B.Tech Computer Science @DelhiTechnologicalUniversity

Software Development EngineerDelhi, India
언어DartJava

분류

이 저장소가 배포한 패키지

사용 중인 의존성

의존성 목록 3 개

  • flutter{"sdk":"flutter"}
  • flutter_test개발 의존성{"sdk":"flutter"}
  • flutter_lints개발 의존성^3.0.0

프로젝트에 맞는 저장소를 선택하려면?

사용 목적에 따라 검색하고 개발 활동을 비교한 뒤 원본 저장소에서 요구 사항을 확인하세요.

  1. 이름, 작성자 또는 설명으로 검색하고 기술 주제로 범위를 좁힙니다.
  2. 스타, 포크, 최근 푸시를 함께 비교하세요. 스타는 관심의 지표이며 품질을 보장하지 않습니다.
  3. 사용하기 전에 GitHub에서 README, 라이선스, Issues를 확인하세요.

출처 및 관리

“A repository is the most basic element of GitHub.”

GitHub Docs — About repositories ↗