first commit

This commit is contained in:
ksenia312
2024-01-31 14:16:22 +01:00
commit 541fbeaaf3
132 changed files with 6463 additions and 0 deletions
+16
View File
@@ -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)
}
}
}
@@ -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()
}
}