nearby_connections 패키지는 Android의 근접 연결 API와 Flutter를 통합하여 블루투스, Wi-Fi 및 NFC를 통해 기기 간 피어 투 피어 통신을 가능하게 합니다. 이 패키지는 원시 바이트 및 파일 전송을 모두 지원하며, 위치 기반 애플리케이션에서 로컬 데이터 공유에 적합합니다. 가볍고 Android 전용으로 설계되어 신뢰성 있고 낮은 지연 시간의 연결을 위해 네이티브 기능을 활용합니다. 인터넷 의존 없이 직접 기기 간 상호작용이 필요한 협업 앱, 멀티플레이어 게임 또는 파일 공유 도구에 유용합니다.
사용 사례
장치 간 로컬 파일 공유
실시간 멀티플레이어 게임 동기화
그룹 설정에서의 오프라인 데이터 교환
장치 간 통신의 빠른 설정
클라우드 백엔드 없이 협업 앱 기능
주요 기능
바이트 및 파일 전송을 지원합니다
Android의 네이티브 근처 연결 API를 사용합니다
저지연, 단거리 통신에 최적화됨
Android용 간단한 Flutter 인터페이스
내장된 탐색 및 연결 관리
적합한 대상
Android 전용 앱으로 로컬 장치 연결이 필요함
빠른 오프라인 데이터 전송이 필요한 앱
협업 또는 소셜 기능을 구축하는 개발자
인터넷 또는 클라우드 서비스에 의존하지 않는 프로젝트
근접 기반 상호작용을 위한 프로토타입
고려 사항
Android 플랫폼만 지원
적절한 권한(블루투스, 위치)이 필요합니다
iOS 지원 없음
근처 연결과의 기기 호환성에 따라 다릅니다
백그라운드 작업은 안드로이드 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
Add these to your project's android/src/main/AndroidManifest.xml
<!-- Required for Nearby Connections --><uses-permissionandroid:maxSdkVersion="31"android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permissionandroid:maxSdkVersion="31"android:name="android.permission.CHANGE_WIFI_STATE" /><uses-permissionandroid:maxSdkVersion="30"android:name="android.permission.BLUETOOTH" /><uses-permissionandroid:maxSdkVersion="30"android:name="android.permission.BLUETOOTH_ADMIN" /><uses-permissionandroid:maxSdkVersion="28"android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permissionandroid:minSdkVersion="29"android:maxSdkVersion="31"android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permissionandroid:minSdkVersion="31"android:name="android.permission.BLUETOOTH_ADVERTISE" /><uses-permissionandroid:minSdkVersion="31"android:name="android.permission.BLUETOOTH_CONNECT" /><uses-permissionandroid:minSdkVersion="31"android:name="android.permission.BLUETOOTH_SCAN" /><uses-permissionandroid:minSdkVersion="32"android:name="android.permission.NEARBY_WIFI_DEVICES" /><!-- Optional: only required for FILE payloads --><uses-permissionandroid: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.
try {
bool a = awaitNearby().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 = awaitNearby().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 methodtry{
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 properlyNearby().sendFilePayload(endpointId, filePath);
//Send filename as well so that receiver can move and rename the fileNearby().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';
awaitNearby().copyFileAndDeleteOriginal(uri, newPath);
Checkout the Example in Repository for more details.