updated nearby to version 17.0.0, added location enabling and checking utility method, version 1.1.0 published

multipeer_ios
Prerak Mann 4 years ago
parent 0f2a651519
commit d89c8b3211

@ -1,3 +1,10 @@
## 1.1.0
* Updated Android Nearby version from 16.0.0 to 17.0.0
* Updated Example
* **Location/GPS service must be turned on** or devices may disconnect
more often, some devices may disconnect immediately. 2 convinience methods are added
`enableLocationServices` and `checkLocationEnabled`
## 1.0.3 ## 1.0.3
* Added serviceId parameter in startAdvertising and startDiscovery * Added serviceId parameter in startAdvertising and startDiscovery

@ -20,6 +20,11 @@ Currently supports Bytes and Files.
## Setup ## Setup
### Note regarding Location(GPS)
While using this,
**Location/GPS service must be turned on** or devices may disconnect
more often, some devices may disconnect immediately.
### Set Permissions ### Set Permissions
Add these to AndroidManifest.xml Add these to AndroidManifest.xml
```xml ```xml
@ -38,7 +43,7 @@ Add these to AndroidManifest.xml
Since ACCESS_FINE_LOCATION and READ_EXTERNAL_STORAGE is considered to be dangerous system permissions, in addition to adding them to your manifest, you must request these permissions at runtime. Since ACCESS_FINE_LOCATION and READ_EXTERNAL_STORAGE is considered to be dangerous system permissions, in addition to adding them to your manifest, you must request these permissions at runtime.
#### As a **convinience** this library provides methods to check and request location and external read/write permissions #### As a **convinience** this library provides methods to check and request location and external read/write permissions
```java ```dart
// returns true/false asynchronously // returns true/false asynchronously
bool a = await Nearby().checkLocationPermissions() bool a = await Nearby().checkLocationPermissions()
// asks for permission only if its not given // asks for permission only if its not given
@ -56,6 +61,18 @@ Nearby().askLocationAndExternalStoragePermission() // for all permissions in one
The work flow is similar to the [Android Nearby Connections library](https://developers.google.com/nearby/connections/overview) The work flow is similar to the [Android Nearby Connections library](https://developers.google.com/nearby/connections/overview)
## NOTE
**Location/GPS service must be turned on** or devices may disconnect
more often, some devices may disconnect immediately.
For convinience this library provides methods to check and enable location
```dart
bool b = await Nearby().checkLocationEnabled();
// opens settings where user can enable it
Nearby().enableLocationServices();
```
### Advertise for connection ### Advertise for connection
```dart ```dart
try { try {

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>nearby_connections</name>
<comment>Project android created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

@ -0,0 +1,13 @@
arguments=
auto.sync=false
build.scans.enabled=false
connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(6.3))
connection.project.dir=../example/android
eclipse.preferences.version=1
gradle.user.home=
java.home=/usr/lib/jvm/java-11-openjdk-amd64
jvm.arguments=
offline.mode=false
override.workspace.settings=true
show.console.view=true
show.executions.view=true

@ -32,6 +32,6 @@ android {
disable 'InvalidPackage' disable 'InvalidPackage'
} }
dependencies{ dependencies{
api 'com.google.android.gms:play-services-nearby:16.0.0' api 'com.google.android.gms:play-services-nearby:17.0.0'
} }
} }

@ -2,7 +2,10 @@ package com.pkmnapps.nearby_connections;
import android.Manifest; import android.Manifest;
import android.app.Activity; import android.app.Activity;
import android.content.Intent;
import android.location.LocationManager;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.provider.Settings;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityCompat;
@ -63,42 +66,61 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
switch (call.method) { switch (call.method) {
case "checkLocationPermission": case "checkLocationPermission":
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) if (ContextCompat.checkSelfPermission(activity,
== PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
== PackageManager.PERMISSION_GRANTED) { && ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
result.success(true); result.success(true);
} else { } else {
result.success(false); result.success(false);
} }
break; break;
case "askLocationPermission": case "askLocationPermission":
ActivityCompat.requestPermissions(activity, ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.ACCESS_FINE_LOCATION,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, Manifest.permission.ACCESS_COARSE_LOCATION }, 0);
0); Log.d("nearby_connections", "askLocationPermission");
Log.d("nearby_connections", "askLocationPermission");
result.success(null); result.success(null);
break; break;
case "checkLocationEnabled":
LocationManager lm = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
result.success(gps_enabled || network_enabled);
break;
case "enableLocationServices":
activity.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
break;
case "checkExternalStoragePermission": case "checkExternalStoragePermission":
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) if (ContextCompat.checkSelfPermission(activity,
== PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
== PackageManager.PERMISSION_GRANTED) { && ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
result.success(true); result.success(true);
} else { } else {
result.success(false); result.success(false);
} }
break; break;
case "askExternalStoragePermission": case "askExternalStoragePermission":
ActivityCompat.requestPermissions(activity, ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
1); Log.d("nearby_connections", "askExternalStoragePermission");
Log.d("nearby_connections", "askExternalStoragePermission");
result.success(null); result.success(null);
break; break;
case "askLocationAndExternalStoragePermission": case "askLocationAndExternalStoragePermission":
ActivityCompat.requestPermissions(activity, ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, new String[] { Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE },
1); 1);
Log.d("nearby_connections", "askExternalStoragePermission"); Log.d("nearby_connections", "askExternalStoragePermission");
result.success(null); result.success(null);
break; break;
case "stopAdvertising": case "stopAdvertising":
@ -117,23 +139,21 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
String serviceId = (String) call.argument("serviceId"); String serviceId = (String) call.argument("serviceId");
assert userNickName != null; assert userNickName != null;
if(serviceId==null || serviceId =="") if (serviceId == null || serviceId == "")
serviceId=SERVICE_ID; serviceId = SERVICE_ID;
AdvertisingOptions advertisingOptions = new AdvertisingOptions.Builder() AdvertisingOptions advertisingOptions = new AdvertisingOptions.Builder()
.setStrategy(getStrategy(strategy)).build(); .setStrategy(getStrategy(strategy)).build();
Nearby.getConnectionsClient(activity) Nearby.getConnectionsClient(activity).startAdvertising(userNickName, serviceId,
.startAdvertising( advertConnectionLifecycleCallback, advertisingOptions)
userNickName, serviceId, advertConnectionLifecycleCallback, advertisingOptions)
.addOnSuccessListener(new OnSuccessListener<Void>() { .addOnSuccessListener(new OnSuccessListener<Void>() {
@Override @Override
public void onSuccess(Void aVoid) { public void onSuccess(Void aVoid) {
Log.d("nearby_connections", "startAdvertising"); Log.d("nearby_connections", "startAdvertising");
result.success(true); result.success(true);
} }
}) }).addOnFailureListener(new OnFailureListener() {
.addOnFailureListener(new OnFailureListener() {
@Override @Override
public void onFailure(@NonNull Exception e) { public void onFailure(@NonNull Exception e) {
result.error("Failure", e.getMessage(), null); result.error("Failure", e.getMessage(), null);
@ -147,11 +167,11 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
String serviceId = (String) call.argument("serviceId"); String serviceId = (String) call.argument("serviceId");
assert userNickName != null; assert userNickName != null;
if(serviceId==null || serviceId =="") if (serviceId == null || serviceId == "")
serviceId=SERVICE_ID; serviceId = SERVICE_ID;
DiscoveryOptions discoveryOptions = DiscoveryOptions discoveryOptions = new DiscoveryOptions.Builder().setStrategy(getStrategy(strategy))
new DiscoveryOptions.Builder().setStrategy(getStrategy(strategy)).build(); .build();
Nearby.getConnectionsClient(activity) Nearby.getConnectionsClient(activity)
.startDiscovery(serviceId, endpointDiscoveryCallback, discoveryOptions) .startDiscovery(serviceId, endpointDiscoveryCallback, discoveryOptions)
.addOnSuccessListener(new OnSuccessListener<Void>() { .addOnSuccessListener(new OnSuccessListener<Void>() {
@ -160,8 +180,7 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
Log.d("nearby_connections", "startDiscovery"); Log.d("nearby_connections", "startDiscovery");
result.success(true); result.success(true);
} }
}) }).addOnFailureListener(new OnFailureListener() {
.addOnFailureListener(new OnFailureListener() {
@Override @Override
public void onFailure(@NonNull Exception e) { public void onFailure(@NonNull Exception e) {
result.error("Failure", e.getMessage(), null); result.error("Failure", e.getMessage(), null);
@ -196,8 +215,7 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
public void onSuccess(Void aVoid) { public void onSuccess(Void aVoid) {
result.success(true); result.success(true);
} }
}) }).addOnFailureListener(new OnFailureListener() {
.addOnFailureListener(new OnFailureListener() {
@Override @Override
public void onFailure(@NonNull Exception e) { public void onFailure(@NonNull Exception e) {
result.error("Failure", e.getMessage(), null); result.error("Failure", e.getMessage(), null);
@ -209,15 +227,13 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
String endpointId = (String) call.argument("endpointId"); String endpointId = (String) call.argument("endpointId");
assert endpointId != null; assert endpointId != null;
Nearby.getConnectionsClient(activity) Nearby.getConnectionsClient(activity).acceptConnection(endpointId, payloadCallback)
.acceptConnection(endpointId, payloadCallback)
.addOnSuccessListener(new OnSuccessListener<Void>() { .addOnSuccessListener(new OnSuccessListener<Void>() {
@Override @Override
public void onSuccess(Void aVoid) { public void onSuccess(Void aVoid) {
result.success(true); result.success(true);
} }
}) }).addOnFailureListener(new OnFailureListener() {
.addOnFailureListener(new OnFailureListener() {
@Override @Override
public void onFailure(@NonNull Exception e) { public void onFailure(@NonNull Exception e) {
result.error("Failure", e.getMessage(), null); result.error("Failure", e.getMessage(), null);
@ -229,15 +245,13 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
String endpointId = (String) call.argument("endpointId"); String endpointId = (String) call.argument("endpointId");
assert endpointId != null; assert endpointId != null;
Nearby.getConnectionsClient(activity) Nearby.getConnectionsClient(activity).rejectConnection(endpointId)
.rejectConnection(endpointId)
.addOnSuccessListener(new OnSuccessListener<Void>() { .addOnSuccessListener(new OnSuccessListener<Void>() {
@Override @Override
public void onSuccess(Void aVoid) { public void onSuccess(Void aVoid) {
result.success(true); result.success(true);
} }
}) }).addOnFailureListener(new OnFailureListener() {
.addOnFailureListener(new OnFailureListener() {
@Override @Override
public void onFailure(@NonNull Exception e) { public void onFailure(@NonNull Exception e) {
result.error("Failure", e.getMessage(), null); result.error("Failure", e.getMessage(), null);
@ -269,7 +283,7 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
Payload filePayload = Payload.fromFile(file); Payload filePayload = Payload.fromFile(file);
Nearby.getConnectionsClient(activity).sendPayload(endpointId, filePayload); Nearby.getConnectionsClient(activity).sendPayload(endpointId, filePayload);
Log.d("nearby_connections", "sentFilePayload"); Log.d("nearby_connections", "sentFilePayload");
result.success(filePayload.getId()); //return payload id to dart result.success(filePayload.getId()); // return payload id to dart
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Log.e("nearby_connections", "File not found", e); Log.e("nearby_connections", "File not found", e);
result.error("Failure", e.getMessage(), null); result.error("Failure", e.getMessage(), null);
@ -405,8 +419,9 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
} }
@Override @Override
public void onPayloadTransferUpdate(@NonNull String endpointId, @NonNull PayloadTransferUpdate payloadTransferUpdate) { public void onPayloadTransferUpdate(@NonNull String endpointId,
//required for files and streams @NonNull PayloadTransferUpdate payloadTransferUpdate) {
// required for files and streams
Log.d("nearby_connections", "onPayloadTransferUpdate"); Log.d("nearby_connections", "onPayloadTransferUpdate");
Map<String, Object> args = new HashMap<>(); Map<String, Object> args = new HashMap<>();
@ -422,7 +437,8 @@ public class NearbyConnectionsPlugin implements MethodCallHandler {
private final EndpointDiscoveryCallback endpointDiscoveryCallback = new EndpointDiscoveryCallback() { private final EndpointDiscoveryCallback endpointDiscoveryCallback = new EndpointDiscoveryCallback() {
@Override @Override
public void onEndpointFound(@NonNull String endpointId, @NonNull DiscoveredEndpointInfo discoveredEndpointInfo) { public void onEndpointFound(@NonNull String endpointId,
@NonNull DiscoveredEndpointInfo discoveredEndpointInfo) {
Log.d("nearby_connections", "onEndpointFound"); Log.d("nearby_connections", "onEndpointFound");
Map<String, Object> args = new HashMap<>(); Map<String, Object> args = new HashMap<>();
args.put("endpointId", endpointId); args.put("endpointId", endpointId);

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>android</name>
<comment>Project android_ created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

@ -0,0 +1,13 @@
arguments=
auto.sync=false
build.scans.enabled=false
connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER)
connection.project.dir=
eclipse.preferences.version=1
gradle.user.home=
java.home=/usr/lib/jvm/java-11-openjdk-amd64
jvm.arguments=
offline.mode=false
override.workspace.settings=true
show.console.view=true
show.executions.view=true

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>app</name>
<comment>Project app created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

@ -0,0 +1,2 @@
connection.project.dir=..
eclipse.preferences.version=1

@ -1,3 +1,4 @@
android.enableJetifier=true android.enableJetifier=true
android.useAndroidX=true android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536M org.gradle.jvmargs=-Xmx1536M
android.enableR8=true

@ -68,8 +68,8 @@ class _MyBodyState extends State<Body> {
), ),
RaisedButton( RaisedButton(
child: Text("askLocationPermission"), child: Text("askLocationPermission"),
onPressed: () async { onPressed: () {
await Nearby().askLocationPermission(); Nearby().askLocationPermission();
}, },
), ),
RaisedButton( RaisedButton(
@ -88,8 +88,34 @@ class _MyBodyState extends State<Body> {
), ),
RaisedButton( RaisedButton(
child: Text("askExternalStoragePermission"), child: Text("askExternalStoragePermission"),
onPressed: () {
Nearby().askExternalStoragePermission();
},
),
],
),
Divider(),
Text("Location Enabled"),
Wrap(
children: <Widget>[
RaisedButton(
child: Text("checkLocationEnabled"),
onPressed: () async { onPressed: () async {
await Nearby().askExternalStoragePermission(); if (await Nearby().checkLocationEnabled()) {
Scaffold.of(context).showSnackBar(SnackBar(
content:
Text("Location is ON :)")));
} else {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text(
"Location is OFF :(")));
}
},
),
RaisedButton(
child: Text("enableLocationServices"),
onPressed: () {
Nearby().enableLocationServices();
}, },
), ),
], ],
@ -113,7 +139,7 @@ class _MyBodyState extends State<Body> {
showSnackbar("Disconnected: " + id); showSnackbar("Disconnected: " + id);
}, },
); );
showSnackbar("ADVERTISING: "+a.toString()); showSnackbar("ADVERTISING: " + a.toString());
} catch (exception) { } catch (exception) {
showSnackbar(exception); showSnackbar(exception);
} }

@ -108,7 +108,7 @@ packages:
path: ".." path: ".."
relative: true relative: true
source: path source: path
version: "1.0.3" version: "1.1.0"
path: path:
dependency: transitive dependency: transitive
description: description:

@ -163,9 +163,22 @@ class Nearby {
/// ///
/// retruns true/false based on external storage permissions. /// retruns true/false based on external storage permissions.
Future<bool> checkExternalStoragePermission() async => Future<bool> checkExternalStoragePermission() async =>
await _channel.invokeMethod( await _channel.invokeMethod('checkExternalStoragePermission');
'checkExternalStoragePermission',
); /// Convinience method
///
/// Checks if Location/GPS is enabled
///
/// If Location isn't enabled, devices may disconnect often.
/// Some devices may immediately disconnect
Future<bool> checkLocationEnabled() async =>
await _channel.invokeMethod('checkLocationEnabled');
/// Convinience method
///
/// directs user to Location Settings, so they can turn on their Location/GPS
void enableLocationServices() =>
_channel.invokeMethod('enableLocationServices');
/// Convinience method /// Convinience method
/// ///

@ -1,6 +1,6 @@
name: nearby_connections name: nearby_connections
description: Plugin for the android NearbyConnections API. Bytes and Files Supported. description: Plugin for the android NearbyConnections API. Bytes and Files Supported.
version: 1.0.3 version: 1.1.0
homepage: https://github.com/mannprerak2/nearby_connections homepage: https://github.com/mannprerak2/nearby_connections
environment: environment:

Loading…
Cancel
Save