Get Started with p2pkit for Android
Enable your apps to understand their proximity to nearby devices.
API Overview
p2pkit has two very simple to understand APIs:
Lifecycle API | Manages the lifecycle and account validation of p2pkit |
---|---|
Discovery API | Manages all aspects of the discovery functionality |
Download
p2pkit Android is available via our Maven repository, please see Setup.
Get your Application Key
In case you do not yet have an application key you would need to obtain one in the p2pkit Console
Create a new app
Source code for the p2pkit Quickstart app is available on GitHub:
https://github.com/Uepaa-AG/p2pkit-quickstart-android
Setup
p2pkit supports Android version 4.1 (Jelly Bean) and above.
-
Add dependency
Include the p2pkit maven repository and p2pkit dependencies in your gradle build files.
repositories { ... maven { url 'http://p2pkit.io/maven2' } } ... dependencies { ... compile 'ch.uepaa.p2p:p2pkit-android:2.1.3' }
-
Add Runtime Permissions
For Android 6.0 and above apps that use Bluetooth require one of the following runtime permissions. Please note that p2pkit is not accessing any GPS data, nevertheless, the location permission is required for accessing Bluetooth functionality.
ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION
If you need more information how to obtain runtime permissions from your users, refer to Requesting Permissions at Run Time.
-
Set Application ID
If not yet done, head back to the p2pkit console and associate the correct Application ID with your application key. p2pkit will validate the Application ID when launched.
Lifecycle - Initialization
Implement P2PKitStatusListener
to receive lifecycle updates about p2pkit.
private final P2PKitStatusListener mStatusListener = new P2PKitStatusListener() { @Override public void onEnabled() { // ready to start discovery } @Override public void onDisabled() { // p2pkit has been disabled } @Override public void onError(StatusResult statusResult) { // an error occured, handle statusResult } @Override public void onException(Throwable throwable) { // an exception was thrown, reenable p2pkit } };
Enable P2PKit
by calling enable()
using your P2PKitStatusListener
and your personal application key.
P2PKit.enable(Context, APP_KEY, mStatusListener);
Discovery
With p2p discovery you can understand your proximity to nearby devices and broadcast information to them. p2pkit supports discovery, lost, payload and ranging APIs.
Implement DiscoveryListener
to receive P2P discovery and update events.
private final DiscoveryListener mDiscoveryListener = new DiscoveryListener() { @Override public void onStateChanged(final int state) { Log.d("DiscoveryListener", "State changed: " + state); } @Override public void onPeerDiscovered(final Peer peer) { Log.d("DiscoveryListener", "Peer discovered: " + peer.getPeerId() + " with info: " + new String(peer.getDiscoveryInfo())); } @Override public void onPeerLost(final Peer peer) { Log.d("DiscoveryListener", "Peer lost: " + peer.getPeerId()); } @Override public void onPeerUpdatedDiscoveryInfo(Peer peer) { Log.d("DiscoveryListener", "Peer updated: " + peer.getPeerId() + " with new info: " + new String(peer.getDiscoveryInfo())); } @Override public void onProximityStrengthChanged(Peer peer) { Log.d("DiscoveryListener", "Peer " + peer.getPeerId() + " changed proximity strength: " + peer.getProximityStrength()); } };
Start p2p discovery and pass in additional discovery info (max 440 bytes) and the desired DiscoveryPowerMode. The discovery info will be received by nearby peers.
P2PKit.startDiscovery("Hello p2pkit".getBytes(), DiscoveryPowerMode.HIGH_PERFORMANCE, mDiscoveryListener);
At a later stage, you can publish new discovery info which will be pushed to nearby peers.
Updates are throttled to one per 60 seconds and disseminated to nearby peers on a best-effort basis. If a nearby peer has lost his connection to our cloud he will not receive the updated version until he is rediscovered.
P2PKit.pushDiscoveryInfo("Hello again".getBytes());
The Discovery Power Mode can be modified at any time by calling:
P2PKit.setDiscoveryPowerMode(DiscoveryPowerMode.LOW_POWER);
Important: Please make sure you stopDiscovery()
when your end-user no longer wishes to discover or be discovered.
Discovery info is transferred over our cloud, however, it is not end-to-end encrypted. Hence we recommend not sending any sensitive data through this means.
Background and DOZE
By default, p2pkit runs as a library within the context of your app and does not implement any special background handling. Simply put: p2pkit will continue to run as long as your app is running. It is therefore important that you start/stop discovery only when needed.
Remember: you (the developer) are responsible for starting/stopping p2pkit.
DOZE
p2pkit is affected by DOZE just as any other app/library. You can read more about DOZE and possible handling solutions here: Optimizing for Doze and App Standby
Proximity Ranging
Proximity Ranging adds context to the discovery events by providing 5 levels of proximity strength from “immediate” to “extremely weak” (see ProximityStrength
).
You could associate "proximity strength" with distance, but due to the unreliable nature of signal strength (different hardware, environmental conditions, etc.) we preferred not to associate the two. Nevertheless, in many cases you will be able to determine who is the closest peer to you (if he is significantly closer than others).
The first step is to enable Proximity Ranging.
P2PKit.enableProximityRanging();
The proximity strength is a property of the Peer
object. Upon discovery the proximity strength value is attached to the Peer
. Updates are delivered via the callback onProximityStrengthChanged
when the proximity strength of a nearby peer changes.
@Override public void onProximityStrengthChanged(Peer peer) { Log.d("DiscoveryListener", "Peer " + peer.getPeerId() + " changed proximity strength: " + peer.getProximityStrength()); }
If the proximity strength for a peer cannot be determined, the proximity strength value will be ProximityStrength.UNKNOWN
.
- Proximity Ranging only works over BLE.
- Due to the limitations of BLE on Android proximity strength updates can be deferred.
- Not all Android devices have the capability to be ranged by other peers.
Messaging
Important: Messaging is only available for Pro Edition accounts.
Messaging can be used to interact with a nearby peer following a discovery event. Contrary to the broadcast nature of the discovery info, a message is always directed to a single recipient.
Sending messages
Once a peer is discovered, you can send him a message like this.
byte[] message = "hello".getBytes(); P2PKit.sendMessageToNearbyPeer(message, peer, new MessageDeliveryStatusHandler() { @Override public void onMessageSendSucceeded() { Log.d("MessageDeliveryHandler", "Message sent to peer: " + peer.getPeerId()); } @Override public void onMessageSendFailed(int errorCode) { Log.d("MessageDeliveryHandler", "Failed to send the message with error code: " + errorCode); } });
Provide a MessageDeliveryStatusHandler
, which will notify you about the status of the message.
Messages can only be sent to currently discovered peers while both are online. The delivery of the message is best-effort, the API limited to 20 messages per second and cannot exceed the size of 100KB.
Receiving messages
To receive messages implement the MessageListener
.
private final MessageListener mMessageListener = new MessageListener() { @Override public void onMessageReceived(byte[] message, Peer peer) { Log.d("MessageListener", peer.getPeerId() + " has sent a message: " + new String(message)); } };
Don't forget to register your listener as a message listener.
P2PKit.addMessageListener(mMessageListener);
You should also unregister the listener, as soon as you are no longer interested in receiving messages.
P2PKit.removeMessageListener(mMessageListener);
Messages are transferred over our cloud, however, they are not end-to-end encrypted. Hence we recommend not sending any sensitive data through this means.
Permissions
In addition to the runtime permission mentioned above, p2pkit requires the following non-runtime permissions which will be automatically merged to your app's manifest.
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Documentation
For detailed information about the api calls, please refer to the Javadoc documentation.
License
By using p2pkit you agree to abide by our Terms of Service, License Agreement and Policies which are available at the following address:
http://p2pkit.io/policy.html