This Android Unity plug-in includes all of the Android WiFi Direct sample Java code used to create the plug-in that you are welcome to use as a starting point to create even more robust WiFi Direct plug-ins or projects of your own.
However, it is not necessary to modify or even build this code if your only interest is to use this sample plug-in as is in your own unity project. This repository contains a build of the WiFiDirectSDActivity-debug.AAR file located in the project folder
\WiFiDirectSDActivity\build\outputs\aar
that you can include in your Unity project and begin using right away.
(See below for details on how to include in your Unity project, and for this Unity plug-in's APIs)
📝NOTE: This plug-in extends the
UnityPlayerActivity
class and contains Unity Editor version specific copies ofUnityPlayerActivity.java
andclasses.jar
files from Unity version:2022.3.6f1
. To use this plug-in in other versions of Unity you may need to clone this project, replace those two files, and rebuild the AAR file to include in your Unity project. (See below for pointers on rebuilding plug-in for other versions of Unity)
For those that are interested in working with the plug-in code, after cloning this respository to your local machine, open the project folder in Android Studio or the Android code editor of your choosing.
The WiFiDirectSDActivity
module contains the source code for a basic Unity Plug-in with peer-to-peer support leveraging Android's flavor of WiFi Direct Service Discovery and a simple implementation of Java Sockets.
Within Android Studio, build the ARR file by first selecting the module in the Project
pane, and then selecting the Make Module 'WiFiDirectPluginHarness.WiFiDirectSDActivity'
from the Build
menu. The ARR file will get generated in the output folder mentioned above.
📝NOTE: Once the ARR file has been added into a Unity project, it is advised to close the Unity project, copy over any new build of the ARR file after each modify/rebuild of the plug-in in Android Studio, and then reopen the Unity project in order to see and test any changes.
The code in this plug-in has been organized into five code modules:
-
WDPluginActivity.java
- Contains the majority of the plug-in logic and overrides the needed
Activity
events
- Contains the majority of the plug-in logic and overrides the needed
-
WiFiDirectBroadcastReceiver.java
- Overrides the needed
BroadcastReceiver
events to handle the relevant WiFi P2P Intents
- Overrides the needed
-
ServerClass.java
- Socket Server class that also manages a multi-threaded array of
ClientHandler
objects when the current device is a WiFi Direct Host managing one or more connected WiFi Direct peer devices
- Socket Server class that also manages a multi-threaded array of
-
ClientHandler.java
ClientHandler
that handles socket communication to a peer from the socket server
-
ClientClass.java
- Client class that handles socket communication to the socket server when the current device is a WiFi Direct peer connected to a WiFi Direct Host
Unfortunately, clear documentation on how the Android WiFi Direct Service Discovery APIs work is hard to find.
The following interpretation is based on the research and experimention conducted while creating this sample, however, it should not be considered an authoritative source for how WiFi Direct Service Discovery is implemented in the Android or AOSP operating system.
WiFi Direct Service Discovery involves one device registering and then broadcasting a service that other devices within range can then discover and connect to.
The plug-in is basically an Android Activity
that uses the following activitiy lifecycle events in the following way:
- add WiFi Direct P2P
intent-filters
to listen for WiFi Direct related broadcasts - initialize P2P services
- check device & hardware capabilities
- create P2P manager and primary objects
- warm up services
- standardize name of device
- request needed permissions
- register broadcast receiver
- unregister broadcast receiver
- close any open connections with other devices
- update connection status
- instantiate and start service
- initiate service discovery
- listen for service broadcasts
- device doing the discovery can initiate a connection to a discovered service host
- clear local services
- clear service discovery requests
- handles incomming notifications of
- device changed
- connection changed
- peers changed
- state changed
- listens for connection update details
This plug-in includes a simple version of string-based messaging between peers using Java Sockets.
The WiFi Direct Service Discovery host device in the shared experience runs a socket server and manages a multi-threaded array of client handlers to deal with each peer.
Peers, on the other hand, act as socket clients that connect and communicate to the host's socket server.
📝NOTE: By default, the thread pool size has been set to handle 10 simultaneous client handlers which, as is, should accomodate up to 11 devices in a shared experience. However, WiFi Direct Service Discovery is capable of connecting many more P2P devices in a session if you are interested in creating a more robust threading solution to manage socket client handlers.
To use this plug-in:
- Copy the .ARR file into your Unity project under
- Assets|Plugins|Android
- Modify the package and activity sections of the Android
Manifest
file located in the same folder to include:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package=
+"com.magicleap.samples.wifidirectsdactivity"
mlns:tools="http://schemas.android.com/tools">
<application>
<activity android:name=
+"com.magicleap.samples.wifidirectsdactivity.WDPluginActivity"
android:theme="@style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
…
- Add a
gamecomponent
to your scene called "WifiDirectPluginManager
" and attach a script that initializes the plug-in and then sets the Wi-Fi Direct Service Name for your application.
AndroidJavaClass unityClass;
AndroidJavaObject unityActivity;
void Start()
{
unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
unityActivity.Call("SetServiceName", Application.productName);
}
- Use the "
unityActivity
" instance to call plug-in functions
for example:
public void StartHosting()
{
if (unityActivity != null)
{
unityActivity.Call("StartHosting");
}
}
- Create public methods to handle plug-in callback
for example:
public void DisplayHostServiceFriendlyName(string serviceFriendlyName)
{
// code to respond to plug-in call to display host service friendly name
}
For a full working sample of a Unity project that implements this plug-in, please refer to our WiFi-Direct-Shared-Experience-Sample code sample project for Unity.
unityActivity.Call("SetServiceName", newServiceName);
Passes: string containing the name of the Wi-Fi Direct Service to broadcast or to filter discovery for
📝NOTE: By setting the service name to the application name (or any other valid unique name) your application will then have its own service to broadcast, discover, and connect to between peer devices. This simplifies the connection options for the user and makes it much more likely to connect to a compatible connection. This service name should be set at plug-in initialization and typically not changed.
string serviceName = unityActivity.Call<string>("GetServiceName");
Returns: string containing the service name being used to broadcast, or to filter discovery of Wi-Fi Direct services
string deviceName = unityActivity.Call<string>("GetDeviceName");
unityActivity.Call("StartHosting");
unityActivity.Call("StopHosting");
unityActivity.Call("StartDiscovering");
unityActivity.Call("StopDiscovering");
unityActivity.Call("ConnectToService", serviceList[index]);
unityActivity.Call("SendCommandToPeers", command);
unityActivity.Call("SendMsgToPeer");
UnityPlayer.UnitySendMessage("WifiDirectPluginManager","DisplayHostServiceFriendlyName", friendlyServiceName);
Updated as a result of:
- StartHosting
- StopHosting
- Loss of connection
UnityPlayer.UnitySendMessage("WifiDirectPluginManager","DisplayConnectedDevices", devices);
Updated from the following plug-in routines:
- ConnectToService
- Peer established connection
- Loss of connection
UnityPlayer.UnitySendMessage("WifiDirectPluginManager","DisplayAvailableServices", services);
Updated as a result of:
- StopDiscovering
- A service is discovered.
UnityPlayer.UnitySendMessage("WifiDirectPluginManager","DisplayDiscoveryStatus",status);
Updated as a result of:
- StartDiscoverying
- StopDiscoverying
- ConnectToService
UnityPlayer.UnitySendMessage("WifiDirectPluginManager","DisplayConnectedServiceFriendlyName",friendlyServiceName);
Updated as a result of:
- ConnectToService
- Loss of connection
UnityPlayer.UnitySendMessage("WifiDirectPluginManager","DisplayIncomingMsg",msg);
Updated as a result of:
- Incomming message received
UnityPlayer.UnitySendMessage("WifiDirectPluginManager","DisplaySystemMsg",msg);
Updated as a result of:
- System message received
UnityPlayer.UnitySendMessage("WifiDirectPluginManager","HandleIncommingCmd",cmd);
Updated as a result of:
- Incoming shared user interaction command received
📝NOTE: specific shared user interaction command names, arguements, and formating to be defined by the Unity application that consumes the plug-in.
Refer to the
Magic Leap Dev Sample
: WiFi-Direct-Share-Experience-Sample App for an example of one comma-delieted approach to sharing a number of common user interactions between devices.
This plug-in extends the UnityPlayerActivity
class and contains Unity Editor version specific copies of UnityPlayerActivity.java
and classes.jar
files from Unity version: 2022.3.6f1
.
To use this plug-in from within projects based on other versions of Unity you may need to clone this project, replace those two files, and rebuild the AAR file to include in your Unity project.
The two files that need to be replaced in the WiFiDirectSDActivity library of the project are:
WiFiDirectSDActivity/src/main/java/com/magicleap/samples/wifidirectsdactivity/UnityPlayerActivity.java
WiFiDirectSDActivity/libs/classes.jar
They should be replaced with copies from your local installation of the Unity Editor that you are targeting. On Windows installations the files are typically found under:
UnityPlayerActivity.java in
C:\Program Files\Unity\Hub\Editor\[specific version number]\Editor\Data\PlaybackEngines\AndroidPlayer\Source\com\unity3d\player
classes.jar in
C:\Program Files\Unity\Hub\Editor\[specific version number]\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\il2cpp\Release\Classes
After replacing those two files, edit the first line of UnityPlayerActivity.java
file to change the package name from
-package com.unity3d.player;
and replace it with
+package com.magicleap.samples.wifidirectsdactivity;
Build the ARR file by first selecting the module in the Project
pane, and then selecting the Make Module 'WiFiDirectPluginHarness.WiFiDirectSDActivity'
from the Build
menu. The ARR file will get generated in the output folder \WiFiDirectSDActivity\build\outputs\aar
.
Use this newly created version specific version of the AAR file in your Unity project of the same version by placing it in the Assets|Plugins|Android
as described in the above section Using the Plug-in in a Unity project.
If you have questions that are not covered here, please check the Magic Leap 2 Developer Forum: https://forum.magicleap.cloud/
Copyright (c) (2023) Magic Leap, Inc. All Rights Reserved. Use of this file is governed by the Developer Agreement, located here: https://www.magicleap.com/software-license-agreement-ml2