first commit
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/workspace.xml
|
||||
/.idea/libraries
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.cxx
|
||||
@@ -0,0 +1,70 @@
|
||||
group 'com.xenikii.nearby_service'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
buildscript {
|
||||
ext.kotlin_version = '1.7.10'
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:7.3.1'
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'kotlin-android'
|
||||
|
||||
android {
|
||||
compileSdk 33
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = '1.8'
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
main.java.srcDirs += 'src/main/kotlin'
|
||||
test.java.srcDirs += 'src/test/kotlin'
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 24
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation 'org.jetbrains.kotlin:kotlin-test'
|
||||
testImplementation 'org.mockito:mockito-core:5.0.0'
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.all {
|
||||
useJUnitPlatform()
|
||||
|
||||
testLogging {
|
||||
events "passed", "skipped", "failed", "standardOut", "standardError"
|
||||
outputs.upToDateWhen { false }
|
||||
showStandardStreams = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'androidx.appcompat:appcompat:1.6.1'
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.6.1'
|
||||
}
|
||||
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+91
@@ -0,0 +1,91 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = 'nearby_service'
|
||||
@@ -0,0 +1,16 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.xenikii.nearby_service">
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.wifi.direct"
|
||||
android:required="true" />
|
||||
</manifest>
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.xenikii.nearby_service
|
||||
|
||||
import android.net.wifi.p2p.WifiP2pDevice
|
||||
import android.net.wifi.p2p.WifiP2pInfo
|
||||
import org.json.JSONObject
|
||||
|
||||
fun WifiP2pDevice.toJsonString(): String {
|
||||
val jsonObject = JSONObject()
|
||||
jsonObject.put("deviceName", deviceName)
|
||||
jsonObject.put("deviceAddress", deviceAddress)
|
||||
jsonObject.put("isGroupOwner", isGroupOwner)
|
||||
jsonObject.put("isServiceDiscoveryCapable", isServiceDiscoveryCapable)
|
||||
jsonObject.put("primaryDeviceType", primaryDeviceType)
|
||||
jsonObject.put("secondaryDeviceType", secondaryDeviceType)
|
||||
jsonObject.put("wpsDisplaySupported", wpsDisplaySupported())
|
||||
jsonObject.put("wpsPbcSupported", wpsPbcSupported())
|
||||
jsonObject.put("wpsKeypadSupported", wpsKeypadSupported())
|
||||
jsonObject.put("status", status)
|
||||
return jsonObject.toString()
|
||||
|
||||
}
|
||||
|
||||
fun WifiP2pInfo.toJsonString(): String {
|
||||
val jsonObject = JSONObject()
|
||||
jsonObject.put("groupFormed", groupFormed)
|
||||
jsonObject.put("groupOwnerAddress", groupOwnerAddress)
|
||||
jsonObject.put("isGroupOwner", isGroupOwner)
|
||||
return jsonObject.toString()
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.xenikii.nearby_service
|
||||
|
||||
import android.util.Log
|
||||
|
||||
const val TAG = "NearbyService"
|
||||
|
||||
/**
|
||||
* Class for systemizing log levels.
|
||||
*/
|
||||
enum class LogLevel(val value: Int) {
|
||||
DEBUG(1),
|
||||
INFO(2),
|
||||
ERROR(3),
|
||||
DISABLED(4),
|
||||
}
|
||||
|
||||
class Logger {
|
||||
companion object {
|
||||
var level = LogLevel.DEBUG
|
||||
fun d(message: String) {
|
||||
if (level.value <= LogLevel.DEBUG.value) {
|
||||
Log.d(TAG, message)
|
||||
}
|
||||
}
|
||||
|
||||
fun i(message: String) {
|
||||
if (level.value <= LogLevel.INFO.value) {
|
||||
Log.i(TAG, message)
|
||||
}
|
||||
}
|
||||
|
||||
fun e(message: String) {
|
||||
if (level.value <= LogLevel.ERROR.value) {
|
||||
Log.e(TAG, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.xenikii.nearby_service
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.wifi.p2p.WifiP2pDevice
|
||||
import android.net.wifi.p2p.WifiP2pDeviceList
|
||||
import android.net.wifi.p2p.WifiP2pInfo
|
||||
import android.net.wifi.p2p.WifiP2pManager
|
||||
import android.net.wifi.p2p.WifiP2pManager.Channel
|
||||
import android.os.Build
|
||||
|
||||
/**
|
||||
* Receiver of [WifiP2pManager] changes.
|
||||
*/
|
||||
class NearbyServiceBroadcastReceiver(
|
||||
private val wifiManager: WifiP2pManager,
|
||||
private val wifiChannel: Channel,
|
||||
private val permissionsHandler: NearbyServicePermissionsHandler,
|
||||
) : BroadcastReceiver() {
|
||||
var peers: MutableList<String> = mutableListOf()
|
||||
var connectedDevice: WifiP2pDevice? = null
|
||||
var currentDevice: WifiP2pDevice? = null
|
||||
var wifiInfo: WifiP2pInfo? = null
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
Logger.i("Received action ${intent.action?.replace("android.net.wifi.p2p.", "")}")
|
||||
|
||||
when (intent.action) {
|
||||
WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION -> {
|
||||
logState(intent)
|
||||
writeConnectionInfo()
|
||||
}
|
||||
|
||||
WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION -> {
|
||||
writeDevices()
|
||||
}
|
||||
|
||||
WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {
|
||||
writeConnectionInfo()
|
||||
}
|
||||
|
||||
WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION -> {
|
||||
writeConnectionInfo()
|
||||
}
|
||||
|
||||
WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION -> {
|
||||
writeCurrentDevice(intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun logState(intent: Intent) {
|
||||
when (intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1)) {
|
||||
WifiP2pManager.WIFI_P2P_STATE_ENABLED -> {
|
||||
Logger.d("P2P state enabled")
|
||||
}
|
||||
|
||||
else -> {
|
||||
Logger.d("P2P state disabled")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun writeCurrentDevice(intent: Intent) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
||||
@Suppress("DEPRECATION")
|
||||
currentDevice = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE)
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeDevices() {
|
||||
try {
|
||||
wifiManager.requestPeers(
|
||||
wifiChannel
|
||||
) { newPeers: WifiP2pDeviceList ->
|
||||
val list: MutableList<String> = mutableListOf()
|
||||
|
||||
if (newPeers.deviceList.isEmpty() && connectedDevice != null) {
|
||||
connectedDevice = null
|
||||
}
|
||||
for (device: WifiP2pDevice in newPeers.deviceList) {
|
||||
list.add(device.toJsonString())
|
||||
if (device.status == WifiP2pDevice.CONNECTED) {
|
||||
connectedDevice = device
|
||||
} else if (device.deviceAddress == connectedDevice?.deviceAddress &&
|
||||
device.status != WifiP2pDevice.CONNECTED
|
||||
) {
|
||||
connectedDevice = null
|
||||
}
|
||||
}
|
||||
peers = list
|
||||
}
|
||||
} catch (e: SecurityException) {
|
||||
if (!permissionsHandler.checkPermissions()) {
|
||||
Logger.e("No permission to call 'writeDevices'")
|
||||
permissionsHandler.requestPermissions()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun writeConnectionInfo() {
|
||||
wifiManager.requestConnectionInfo(wifiChannel) { info: WifiP2pInfo ->
|
||||
if (!info.groupFormed && wifiInfo?.groupFormed == true) {
|
||||
writeDevices()
|
||||
}
|
||||
wifiInfo = info
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package com.xenikii.nearby_service
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.net.wifi.WifiManager
|
||||
import android.net.wifi.WpsInfo
|
||||
import android.net.wifi.p2p.WifiP2pConfig
|
||||
import android.net.wifi.p2p.WifiP2pManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.Settings
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
|
||||
import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodChannel.Result
|
||||
import kotlinx.coroutines.future.await
|
||||
|
||||
/**
|
||||
* General Manager of Wi-fi Direct local network operations.
|
||||
*/
|
||||
class NearbyServiceManager(private var context: Context) {
|
||||
private lateinit var wifiManager: WifiP2pManager
|
||||
private lateinit var wifiChannel: WifiP2pManager.Channel
|
||||
private lateinit var receiver: NearbyServiceBroadcastReceiver
|
||||
|
||||
private val intentFilter = IntentFilter()
|
||||
private var permissionsHandler = NearbyServicePermissionsHandler(context)
|
||||
private var activityPluginBinding: ActivityPluginBinding? = null
|
||||
|
||||
|
||||
/**
|
||||
* Sets [binding] to [activityPluginBinding] and [permissionsHandler].
|
||||
* Adds permissions result listener to [binding].
|
||||
*/
|
||||
fun setBinding(binding: ActivityPluginBinding) {
|
||||
activityPluginBinding = binding
|
||||
activityPluginBinding?.addRequestPermissionsResultListener(permissionsHandler)
|
||||
permissionsHandler.activity = binding.activity
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes permissions result listener to [activityPluginBinding].
|
||||
* Sets [activityPluginBinding] to null.
|
||||
*/
|
||||
fun removeBinding() {
|
||||
activityPluginBinding?.removeRequestPermissionsResultListener(permissionsHandler)
|
||||
activityPluginBinding = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes everything for [WifiManager] to work.
|
||||
*/
|
||||
fun initialize(result: Result, logLevel: String) {
|
||||
Logger.level = LogLevel.valueOf(logLevel.uppercase())
|
||||
|
||||
addWifiActions()
|
||||
initWifiManager()
|
||||
initReceiver()
|
||||
result.success(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Requesting permissions with [permissionsHandler].
|
||||
*/
|
||||
suspend fun requestPermissions(): Boolean {
|
||||
return permissionsHandler.requestPermissionsAsync().await()
|
||||
}
|
||||
|
||||
/**
|
||||
* Checking if Wi-fi is enabled now.
|
||||
*/
|
||||
fun checkWifiService(result: Result) {
|
||||
result.success(
|
||||
(context.getSystemService(Context.WIFI_SERVICE) as WifiManager).isWifiEnabled
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns info about a current device in format WifiP2pDevice.toJsonString().
|
||||
*
|
||||
* Note!
|
||||
* The field **deviceAddress** will always be 02:00:00:00:00:00 for privacy issues.
|
||||
*
|
||||
* Note!
|
||||
* If the SDK version is less than 29 (Q), tries to return a current device from [receiver].
|
||||
* It also may be null.
|
||||
*/
|
||||
fun getCurrentDevice(result: Result) {
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
wifiManager.requestDeviceInfo(wifiChannel) { device ->
|
||||
result.success(device?.toJsonString())
|
||||
}
|
||||
} else {
|
||||
result.success(receiver.currentDevice?.toJsonString())
|
||||
}
|
||||
} catch (e: SecurityException) {
|
||||
if (!permissionsHandler.checkPermissions()) {
|
||||
Logger.e("No permission to call 'discover'")
|
||||
permissionsHandler.requestPermissions()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the phone settings under Wi-fi.
|
||||
*/
|
||||
fun openWifiSettings(result: Result) {
|
||||
activityPluginBinding?.activity?.startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
|
||||
result.success(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Start discovery for peers in Wi-fi Direct scope.
|
||||
*
|
||||
* Note!
|
||||
* All permissions from [NearbyServicePermissionsHandler] are required.
|
||||
*/
|
||||
fun discover(result: Result) {
|
||||
try {
|
||||
wifiManager.discoverPeers(
|
||||
wifiChannel, getActionListener(result)
|
||||
)
|
||||
} catch (e: SecurityException) {
|
||||
if (!permissionsHandler.checkPermissions()) {
|
||||
Logger.e("No permission to call 'discover'")
|
||||
permissionsHandler.requestPermissions()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop discovery for peers in Wi-fi Direct scope.
|
||||
*/
|
||||
fun stopDiscovery(result: Result) {
|
||||
wifiManager.stopPeerDiscovery(
|
||||
wifiChannel, getActionListener(result)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns peers from [NearbyServiceBroadcastReceiver].
|
||||
*/
|
||||
fun getPeers(result: Result) {
|
||||
result.success(receiver.peers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns connection info from [NearbyServiceBroadcastReceiver] in json string.
|
||||
*/
|
||||
fun getConnectionInfo(result: Result) {
|
||||
val info = receiver.wifiInfo?.toJsonString()
|
||||
result.success(info)
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to provided [deviceAddress] in Wi-fi Direct scope.
|
||||
*/
|
||||
fun connect(result: Result, deviceAddress: String) {
|
||||
val config = WifiP2pConfig()
|
||||
if (receiver.connectedDevice?.deviceAddress == deviceAddress) {
|
||||
Logger.i("Already connected to the device $deviceAddress")
|
||||
result.success(true)
|
||||
return
|
||||
}
|
||||
val actionListener = getActionListener(
|
||||
result,
|
||||
"Connected to device $deviceAddress",
|
||||
"Connecting to device $deviceAddress failed"
|
||||
)
|
||||
config.deviceAddress = deviceAddress
|
||||
config.wps.setup = WpsInfo.PBC
|
||||
try {
|
||||
wifiChannel.also { wifiChannel: WifiP2pManager.Channel ->
|
||||
wifiManager.connect(wifiChannel, config, actionListener)
|
||||
}
|
||||
} catch (e: SecurityException) {
|
||||
if (!permissionsHandler.checkPermissions()) {
|
||||
Logger.e("No permission to call 'connect'")
|
||||
permissionsHandler.requestPermissions()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from a previous device in Wi-fi Direct scope.
|
||||
*/
|
||||
fun disconnect(result: Result? = null) {
|
||||
val actionListener = getActionListener(
|
||||
result, "Disconnected from last device", "Failed to disconnect"
|
||||
)
|
||||
wifiManager.removeGroup(wifiChannel, actionListener)
|
||||
|
||||
}
|
||||
|
||||
|
||||
private fun addWifiActions() {
|
||||
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)
|
||||
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)
|
||||
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)
|
||||
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION)
|
||||
intentFilter.addAction(WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION)
|
||||
}
|
||||
|
||||
private fun initWifiManager() {
|
||||
wifiManager = context.getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
|
||||
wifiChannel = wifiManager.initialize(context, Looper.getMainLooper(), null)
|
||||
}
|
||||
|
||||
private fun initReceiver() {
|
||||
receiver = NearbyServiceBroadcastReceiver(
|
||||
wifiManager,
|
||||
wifiChannel,
|
||||
permissionsHandler,
|
||||
)
|
||||
context.registerReceiver(receiver, intentFilter)
|
||||
}
|
||||
|
||||
private fun getActionListener(
|
||||
result: Result?,
|
||||
successMessage: String? = null,
|
||||
errorMessage: String? = null,
|
||||
): WifiP2pManager.ActionListener {
|
||||
return object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() {
|
||||
if (successMessage != null) {
|
||||
Logger.i(successMessage)
|
||||
}
|
||||
result?.success(true)
|
||||
}
|
||||
|
||||
override fun onFailure(reasonCode: Int) {
|
||||
if (errorMessage != null) {
|
||||
Logger.e("ERROR: $errorMessage Reason code: $reasonCode")
|
||||
}
|
||||
result?.success(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var peersHandler = object : EventChannel.StreamHandler {
|
||||
private var handler: Handler = Handler(Looper.getMainLooper())
|
||||
private var eventSink: EventChannel.EventSink? = null
|
||||
|
||||
val postCallback = object : Runnable {
|
||||
override fun run() {
|
||||
handler.post { eventSink?.success("${receiver.peers}") }
|
||||
handler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onListen(arguments: Any?, sink: EventChannel.EventSink?) {
|
||||
onCancel(null)
|
||||
Logger.d("Start listening peers")
|
||||
eventSink = sink
|
||||
handler.postDelayed(postCallback, 1000)
|
||||
}
|
||||
|
||||
override fun onCancel(p0: Any?) {
|
||||
Logger.d("Kill last process listening peers")
|
||||
eventSink = null
|
||||
handler.removeCallbacks(postCallback)
|
||||
}
|
||||
}
|
||||
|
||||
var connectedDeviceInfoHandler = object : EventChannel.StreamHandler {
|
||||
private var handler: Handler = Handler(Looper.getMainLooper())
|
||||
private var eventSink: EventChannel.EventSink? = null
|
||||
|
||||
val postCallback = object : Runnable {
|
||||
override fun run() {
|
||||
handler.post { eventSink?.success(receiver.connectedDevice?.toJsonString()) }
|
||||
handler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onListen(arguments: Any?, sink: EventChannel.EventSink?) {
|
||||
onCancel(null)
|
||||
eventSink = sink
|
||||
Logger.d("Listen connected device")
|
||||
handler.postDelayed(postCallback, 1000)
|
||||
}
|
||||
|
||||
override fun onCancel(p0: Any?) {
|
||||
Logger.d("Kill last process connected device")
|
||||
eventSink = null
|
||||
handler.removeCallbacks(postCallback)
|
||||
}
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package com.xenikii.nearby_service
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.annotation.RequiresApi
|
||||
import io.flutter.plugin.common.PluginRegistry
|
||||
import kotlinx.coroutines.future.await
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
/**
|
||||
* Class representing permission.
|
||||
* [name] is official permission name from [Manifest].
|
||||
* [code] is the value with which the permission will be requested - requestCode.
|
||||
*/
|
||||
|
||||
class AppPermission(val name: String, val code: Int) {
|
||||
val future = CompletableFuture<Boolean>()
|
||||
}
|
||||
|
||||
/**
|
||||
* The class responsible for plugin permissions.
|
||||
* It contains different ways of checking and requesting them.
|
||||
* Before you use it, make sure you set the [activity] externally.
|
||||
*/
|
||||
class NearbyServicePermissionsHandler(private var context: Context) :
|
||||
PluginRegistry.RequestPermissionsResultListener {
|
||||
|
||||
var activity: Activity? = null
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
|
||||
private val nearbyPermission = AppPermission(Manifest.permission.NEARBY_WIFI_DEVICES, 98)
|
||||
private val locationPermission = AppPermission(Manifest.permission.ACCESS_FINE_LOCATION, 99)
|
||||
|
||||
|
||||
/**
|
||||
* Sync checking permissions.
|
||||
*/
|
||||
fun checkPermissions(): Boolean {
|
||||
val locationGranted = checkLocationPermission()
|
||||
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
checkNearbyPermission() && locationGranted
|
||||
} else {
|
||||
return locationGranted
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync requesting permissions.
|
||||
*/
|
||||
fun requestPermissions() {
|
||||
Logger.i("Requesting all required permissions")
|
||||
requestLocationPermission()
|
||||
requestNearbyPermission()
|
||||
}
|
||||
|
||||
/**
|
||||
* Async requesting permissions.
|
||||
*/
|
||||
suspend fun requestPermissionsAsync(): CompletableFuture<Boolean> {
|
||||
val res = checkPermissions()
|
||||
if (res) return CompletableFuture.completedFuture(true)
|
||||
|
||||
Logger.i("Requesting all required permissions")
|
||||
return CompletableFuture.completedFuture(
|
||||
requestLocationPermission().await() && requestNearbyPermission().await()
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Requesting location permission [Manifest.permission.ACCESS_FINE_LOCATION]
|
||||
*/
|
||||
private fun requestLocationPermission(): CompletableFuture<Boolean> {
|
||||
if (checkLocationPermission()) {
|
||||
return CompletableFuture.completedFuture(true)
|
||||
}
|
||||
activity?.requestPermissions(
|
||||
arrayOf(locationPermission.name), locationPermission.code
|
||||
)
|
||||
|
||||
return locationPermission.future
|
||||
}
|
||||
|
||||
/**
|
||||
* Requesting nearby devices permission [Manifest.permission.NEARBY_WIFI_DEVICES].
|
||||
* Calls if [Build.VERSION.SDK_INT] is equal or more than [Build.VERSION_CODES.TIRAMISU]
|
||||
*/
|
||||
private fun requestNearbyPermission(): CompletableFuture<Boolean> {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
|
||||
if (checkNearbyPermission()) {
|
||||
return CompletableFuture.completedFuture(true)
|
||||
}
|
||||
|
||||
activity?.requestPermissions(
|
||||
arrayOf(nearbyPermission.name), nearbyPermission.code
|
||||
)
|
||||
return nearbyPermission.future
|
||||
} else {
|
||||
return CompletableFuture.completedFuture(true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checking location permission [Manifest.permission.ACCESS_FINE_LOCATION]
|
||||
*/
|
||||
private fun checkLocationPermission(): Boolean {
|
||||
return context.checkSelfPermission(
|
||||
locationPermission.name
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
/**
|
||||
* Checking nearby devices permission [Manifest.permission.NEARBY_WIFI_DEVICES].
|
||||
* Available if [Build.VERSION.SDK_INT] is equal or more than [Build.VERSION_CODES.TIRAMISU]
|
||||
*/
|
||||
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
|
||||
private fun checkNearbyPermission(): Boolean {
|
||||
return context.checkSelfPermission(
|
||||
nearbyPermission.name
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission result handler.
|
||||
* Completes the future of permission with the provided [requestCode] if it was granted.
|
||||
*/
|
||||
override fun onRequestPermissionsResult(
|
||||
requestCode: Int, permissions: Array<out String>, grantResults: IntArray
|
||||
): Boolean {
|
||||
if (grantResults.isNotEmpty()) {
|
||||
if (requestCode == locationPermission.code) {
|
||||
val isGranted = checkLocationPermission()
|
||||
locationPermission.future.complete(isGranted)
|
||||
Logger.i("Location permission activity result: isGranted=$isGranted")
|
||||
return isGranted
|
||||
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && requestCode == nearbyPermission.code) {
|
||||
val isGranted = checkNearbyPermission()
|
||||
nearbyPermission.future.complete(isGranted)
|
||||
Logger.i("Nearby devices permission activity result: isGranted=$isGranted")
|
||||
return isGranted
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package com.xenikii.nearby_service
|
||||
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityAware
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
|
||||
import io.flutter.plugin.common.MethodChannel.Result
|
||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
|
||||
const val CHANNEL_NAME = "nearby_service"
|
||||
const val PEERS_CHANNEL_NAME = "nearby_service_peers"
|
||||
const val CONNECTED_DEVICE_CHANNEL_NAME = "nearby_service_connected_device"
|
||||
|
||||
/**
|
||||
* Plugin for creating connections in the Wi-fi Direct scope.
|
||||
*/
|
||||
class NearbyServicePlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
|
||||
private lateinit var binaryMessenger: BinaryMessenger
|
||||
private lateinit var channel: MethodChannel
|
||||
private lateinit var manager: NearbyServiceManager
|
||||
private lateinit var peersChannel: EventChannel
|
||||
private lateinit var connectedDeviceChannel: EventChannel
|
||||
|
||||
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
override fun onMethodCall(call: MethodCall, result: Result) {
|
||||
when (call.method) {
|
||||
"getPlatformVersion" -> {
|
||||
result.success("Android ${android.os.Build.VERSION.RELEASE}")
|
||||
}
|
||||
|
||||
"getPlatformModel" -> {
|
||||
result.success(android.os.Build.MODEL)
|
||||
}
|
||||
|
||||
"initialize" -> {
|
||||
try {
|
||||
manager.initialize(result, call.argument("logLevel") ?: "DEBUG")
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
"requestPermissions" -> {
|
||||
GlobalScope.launch {
|
||||
try {
|
||||
result.success(manager.requestPermissions())
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
"getCurrentDevice" -> {
|
||||
try {
|
||||
manager.getCurrentDevice(result)
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
"checkWifiService" -> {
|
||||
try {
|
||||
manager.checkWifiService(result)
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
"openServicesSettings" -> {
|
||||
try {
|
||||
manager.openWifiSettings(result)
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
"discover" -> {
|
||||
try {
|
||||
manager.discover(result)
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
"stopDiscovery" -> {
|
||||
try {
|
||||
manager.stopDiscovery(result)
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
"getPeers" -> {
|
||||
try {
|
||||
manager.getPeers(result)
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
"getConnectionInfo" -> {
|
||||
try {
|
||||
manager.getConnectionInfo(result)
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
"connect" -> {
|
||||
try {
|
||||
manager.connect(result, call.argument("deviceAddress") ?: "")
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
"disconnect" -> {
|
||||
try {
|
||||
manager.disconnect(result)
|
||||
} catch (e: Exception) {
|
||||
onError(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
result.notImplemented()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onError(result: Result, e: Exception) {
|
||||
Logger.e(e.message.toString())
|
||||
result.success(false)
|
||||
}
|
||||
|
||||
override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
|
||||
binaryMessenger = flutterPluginBinding.binaryMessenger
|
||||
manager = NearbyServiceManager(flutterPluginBinding.applicationContext)
|
||||
|
||||
channel = MethodChannel(binaryMessenger, CHANNEL_NAME)
|
||||
channel.setMethodCallHandler(this)
|
||||
|
||||
peersChannel = EventChannel(binaryMessenger, PEERS_CHANNEL_NAME)
|
||||
peersChannel.setStreamHandler(manager.peersHandler)
|
||||
|
||||
connectedDeviceChannel = EventChannel(binaryMessenger, CONNECTED_DEVICE_CHANNEL_NAME)
|
||||
connectedDeviceChannel.setStreamHandler(manager.connectedDeviceInfoHandler)
|
||||
}
|
||||
|
||||
|
||||
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
channel.setMethodCallHandler(null)
|
||||
peersChannel.setStreamHandler(null)
|
||||
connectedDeviceChannel.setStreamHandler(null)
|
||||
manager.disconnect()
|
||||
}
|
||||
|
||||
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
|
||||
manager.setBinding(binding)
|
||||
}
|
||||
|
||||
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
|
||||
manager.setBinding(binding)
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivityForConfigChanges() {
|
||||
manager.removeBinding()
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivity() {
|
||||
manager.removeBinding()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user