-
Notifications
You must be signed in to change notification settings - Fork 14
/
NearbyConnectionModule.java
1912 lines (1593 loc) · 64.1 KB
/
NearbyConnectionModule.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.butchmarshall.reactnative.google.nearby.connection;
import static com.butchmarshall.reactnative.google.nearby.connection.Constants.TAG;
import android.Manifest;
import android.hardware.Camera;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.PromiseImpl;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactMethod;
import android.app.Activity;
import android.net.Uri;
import android.content.Intent;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.annotation.WorkerThread;
import android.support.v4.content.ContextCompat;
import android.support.v4.app.ActivityCompat;
import android.support.v4.util.SimpleArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.connection.AdvertisingOptions;
import com.google.android.gms.nearby.connection.ConnectionInfo;
import com.google.android.gms.nearby.connection.ConnectionLifecycleCallback;
import com.google.android.gms.nearby.connection.ConnectionResolution;
import com.google.android.gms.nearby.connection.ConnectionsClient;
import com.google.android.gms.nearby.connection.ConnectionsStatusCodes;
import com.google.android.gms.nearby.connection.DiscoveredEndpointInfo;
import com.google.android.gms.nearby.connection.DiscoveryOptions;
import com.google.android.gms.nearby.connection.EndpointDiscoveryCallback;
import com.google.android.gms.nearby.connection.Payload;
import com.google.android.gms.nearby.connection.PayloadCallback;
import com.google.android.gms.nearby.connection.PayloadTransferUpdate;
import com.google.android.gms.nearby.connection.Strategy;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
/*import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;*/
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
public class NearbyConnectionModule extends ReactContextBaseJavaModule implements ActivityEventListener {
ReactApplicationContext reactContext;
/**
* These permissions are required before connecting to Nearby Connections. Only {@link
* Manifest.permission#ACCESS_COARSE_LOCATION} is considered dangerous, so the others should be
* granted just by having them in our AndroidManfiest.xml
*/
private static final String[] REQUIRED_PERMISSIONS =
new String[] {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.ACCESS_COARSE_LOCATION,
};
private static final String[] REQUIRED_AUDIO_PERMISSIONS =
new String[] {
Manifest.permission.RECORD_AUDIO,
};
private static final String[] REQUIRED_STORAGE_PERMISSIONS =
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
private static final String E_PERMISSIONS_MISSING = "E_PERMISSION_MISSING";
private static final String E_CALLBACK_ERROR = "E_CALLBACK_ERROR";
private static final int REQUEST_CODE_REQUIRED_PERMISSIONS = 1;
/** For recording audio as the user speaks. */
@Nullable private AudioRecorder mRecorder;
/**
* True if we are asking a discovered device to connect to us. While we ask, we cannot ask another
* device.
*/
private boolean mIsConnecting = false;
/** True if we are discovering. */
private boolean mIsDiscovering = false;
/** True if we are advertising. */
private boolean mIsAdvertising = false;
private final Map<String, ConnectionsClient> mConnectionsClients = new HashMap<>();
/** The devices we've discovered near us. */
private final Map<String, Endpoint> mEndpoints = new HashMap<>();
/** For recording audio as the user speaks. */
private final Map<String, AudioRecorder> mRecorders = new HashMap<>();
private final Map<String, Payload> mReceivedPayloads = new HashMap<>();
private final SimpleArrayMap<String, String> mPayloadFileData = new SimpleArrayMap<>();
private final Map<String, AudioPlayer> mAudioPlayers = new HashMap<>();
/** Callbacks for connections to other devices. */
private ConnectionLifecycleCallback getConnectionLifecycleCallback(final String serviceId, final String type) {
final ConnectionLifecycleCallback mConnectionLifecycleCallback = new ConnectionLifecycleCallback() {
@Override
public void onConnectionInitiated(String endpointId, ConnectionInfo connectionInfo) {
logD(
String.format(
"onConnectionInitiated(serviceId=%s, endpointId=%s, endpointName=%s)",
serviceId, endpointId, connectionInfo.getEndpointName()));
Endpoint endpoint = new Endpoint(serviceId, endpointId, connectionInfo.getEndpointName(), type);
mEndpoints.put(serviceId+"_"+endpointId, endpoint);
connectionInitiatedToEndpoint(serviceId, endpointId, connectionInfo);
}
@Override
public void onConnectionResult(String endpointId, ConnectionResolution result) {
logD(String.format("onConnectionResponse(serviceId=%s, endpointId=%s, result=%s)", serviceId, endpointId, result));
// We're no longer connecting
mIsConnecting = false;
if (!result.getStatus().isSuccess()) {
logW(
String.format(
"Connection failed. Received status %s.",
NearbyConnectionModule.statusToString(result.getStatus())));
endpointConnectionFailed(serviceId, endpointId, result.getStatus().getStatusCode());
return;
}
connectedToEndpoint(serviceId, endpointId);
}
@Override
public void onDisconnected(String endpointId) {
logD(String.format("onDisconnected(serviceId=%s, endpointId=%s)", serviceId, endpointId));
// TODO FIX THIS
if (!mEndpoints.containsKey(serviceId+"_"+endpointId) || !mEndpoints.get(serviceId+"_"+endpointId).isConnected()) {
logW("Unexpected disconnection from serviceId "+serviceId+" and endpoint " + endpointId);
return;
}
closeMicrophone(serviceId, endpointId);
disconnectedFromEndpoint(serviceId, endpointId);
}
};
return mConnectionLifecycleCallback;
}
/** Callbacks for payloads (bytes of data) sent from another device to us. */
private PayloadCallback getPayloadCallback(final String serviceId) {
final PayloadCallback mPayloadCallback = new PayloadCallback() {
@Override
public void onPayloadReceived(String endpointId, Payload payload) {
String payloadId = Long.toString(payload.getId());
int payloadType = payload.getType();
logD(String.format("onPayloadReceived(endpointId=%s, payload=%s, id=%s, type=%s)", endpointId, payload, payloadId, payloadType));
mReceivedPayloads.put(serviceId+"_"+endpointId+"_"+payloadId, payload);
// Track out-of-band filename transfers
if (payloadType == Payload.Type.BYTES) {
String bytes = "";
try {
bytes = new String(payload.asBytes(), "UTF-8");
}
catch (UnsupportedEncodingException e) {
logW("onPayloadReceived failed converting payload asBytes.", e);
}
int colonIndex = bytes.indexOf(':');
int filePayloadType = Integer.parseInt(bytes.substring(0, colonIndex));
if (filePayloadType == Payload.Type.FILE) {
bytes = bytes.substring(colonIndex + 1);
colonIndex = bytes.indexOf(':');
String filePayloadId = bytes.substring(0, colonIndex);
String filename = bytes.substring(colonIndex + 1);
logD(String.format("got filename for (payloadId=%s, filename=%s)", filePayloadId, filename));
mPayloadFileData.put(filePayloadId, filename);
}
}
onReceivePayload(serviceId, endpointId, payload);
}
@Override
public void onPayloadTransferUpdate(String endpointId, PayloadTransferUpdate update) {
logD(String.format("onPayloadTransferUpdate(endpointId=%s, update=%s)", endpointId, update));
onPayloadUpdate(serviceId, endpointId, update);
}
};
return mPayloadCallback;
};
private EndpointDiscoveryCallback getEndpointDiscoveryCallback(final String serviceId) {
final EndpointDiscoveryCallback mEndpointDiscoveryCallback = new EndpointDiscoveryCallback() {
@Override
public void onEndpointFound(String endpointId, DiscoveredEndpointInfo info) {
logD(
String.format(
"onEndpointFound(endpointId=%s, serviceId=%s, endpointName=%s)",
endpointId, info.getServiceId(), info.getEndpointName()));
Endpoint existingEndpoint = mEndpoints.get(serviceId+"_"+endpointId);
if (serviceId.equals(info.getServiceId()) && existingEndpoint == null || !existingEndpoint.isConnected()) {
Endpoint endpoint = new Endpoint(serviceId, endpointId, info.getEndpointName(), "discovering");
mEndpoints.put(serviceId+"_"+endpointId, endpoint);
onEndpointDiscovered(serviceId, endpointId);
}
}
@Override
public void onEndpointLost(String endpointId) {
logD(String.format("onEndpointLost(endpointId=%s)", endpointId));
endpointLost(serviceId, endpointId);
}
};
return mEndpointDiscoveryCallback;
}
public NearbyConnectionModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
onResume();
setLifecycleListeners();
}
private void onResume() {
registerAdvertisingStartingHandler();
registerAdvertisingStartedHandler();
registerAdvertisingStartFailedHandler();
registerDiscoveryStartingHandler();
registerDiscoveryStartedHandler();
registerDiscoveryStartFailedHandler();
registerEndpointDiscoveredHandler();
registerEndpointLostHandler();
registerConnectionInitiatedToEndpointHandler();
registerConnectedToEndpointHandler();
registerDisconnectedFromEndpointHandler();
registerEndpointConnectionFailedHandler();
registerOnReceivePayloadHandler();
registerOnPayloadUpdateHandler();
registerSendPayloadFailedHandler();
}
private void onPause() {
unregisterAdvertisingStartingHandler();
unregisterAdvertisingStartedHandler();
unregisterAdvertisingStartFailedHandler();
unregisterDiscoveryStartingHandler();
unregisterDiscoveryStartedHandler();
unregisterDiscoveryStartFailedHandler();
unregisterEndpointDiscoveredHandler();
unregisterEndpointLostHandler();
unregisterConnectionInitiatedToEndpointHandler();
unregisterConnectedToEndpointHandler();
unregisterDisconnectedFromEndpointHandler();
unregisterEndpointConnectionFailedHandler();
unregisterOnReceivePayloadHandler();
unregisterOnPayloadUpdateHandler();
unregisterSendPayloadFailedHandler();
}
private void onDestroy() {
}
@Override
public void onCatalystInstanceDestroy() {
logW("onCatalystInstanceDestroy");
for (ConnectionsClient mConnectionsClient : mConnectionsClients.values()) {
mConnectionsClient.stopDiscovery();
mConnectionsClient.stopAdvertising();
mConnectionsClient.stopAllEndpoints();
}
}
private void setLifecycleListeners() {
this.reactContext.addLifecycleEventListener(new LifecycleEventListener() {
@Override
public void onHostResume() {
logW("onHostResume");
onResume();
}
@Override
public void onHostPause() {
logW("onHostPause");
onPause();
}
@Override
public void onHostDestroy() {
logW("onHostDestroy");
onDestroy();
}
});
}
/** Called when our Activity is first created. */
protected ConnectionsClient getConnectionsClientSingleton(final String serviceId) {
ConnectionsClient mConnectionsClient = mConnectionsClients.get(serviceId);
if (mConnectionsClient == null) {
logV("No ConnectionsClient exists for " + serviceId + ", initializing");
final Activity currentActivity = getCurrentActivity();
mConnectionsClient = Nearby.getConnectionsClient(currentActivity);
mConnectionsClients.put(serviceId, mConnectionsClient);
}
return mConnectionsClient;
}
@Override
public String getName() {
return "NearbyConnection";
}
@Override
public void onNewIntent(Intent intent) {
}
@Override
public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
}
/**
* Get all the payloads received by this device
*/
@ReactMethod
public void payloads(final Promise promise) {
WritableArray result = Arguments.createArray();
for (String key : mReceivedPayloads.keySet()) {
// Explode key to get serviceId, endpointId, payloadId
//result.pushMap(endpoint.toWritableMap());
}
promise.resolve(result);
}
/**
* Get all the services discovered by this device
*/
@ReactMethod
public void endpoints(final Promise promise) {
WritableArray result = Arguments.createArray();
for (Endpoint endpoint : mEndpoints.values()) {
result.pushMap(endpoint.toWritableMap());
}
promise.resolve(result);
}
@ReactMethod
public void rejectConnection(final String serviceId, final String endpointId) {
final Endpoint endpoint = mEndpoints.get(serviceId+"_"+endpointId);
logV("rejecting connection from " + endpointId);
final ConnectionsClient clientSingleton = getConnectionsClientSingleton(serviceId);
clientSingleton
.rejectConnection(endpointId)
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
ApiException apiException = (ApiException) e;
logW("rejectConnection() failed.", e);
}
});
}
@ReactMethod
public void acceptConnection(final String serviceId, final String endpointId) {
final Endpoint endpoint = mEndpoints.get(serviceId+"_"+endpointId);
logV("acceptConnection(serviceId: "+serviceId+", endpointId:" + endpointId+")");
final ConnectionsClient clientSingleton = getConnectionsClientSingleton(serviceId);
clientSingleton
.acceptConnection(endpointId, getPayloadCallback(serviceId))
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
ApiException apiException = (ApiException) e;
logW("acceptConnection(serviceId: "+serviceId+", endpointId:" + endpointId+") failed.", e);
}
});
}
@ReactMethod
protected void startAdvertising(final String endpointName, final String serviceId, final int strategy) {
mIsAdvertising = true;
onAdvertisingStarting(endpointName, serviceId);
Strategy finalStrategy = Strategy.P2P_CLUSTER;
switch(strategy) {
case 0: finalStrategy = Strategy.P2P_CLUSTER;
break;
case 1: finalStrategy = Strategy.P2P_STAR;
break;
}
final Activity activity = getCurrentActivity();
final ConnectionsClient clientSingleton = getConnectionsClientSingleton(serviceId);
final AdvertisingOptions advertisingOptions = new AdvertisingOptions(finalStrategy);
permissionsCheck(activity, Arrays.asList(getRequiredPermissions()), new Callable<Void>() {
@Override
public Void call() throws Exception {
clientSingleton
.startAdvertising(
endpointName,
serviceId,
getConnectionLifecycleCallback(serviceId, "advertised"),
advertisingOptions
)
.addOnSuccessListener(
new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unusedResult) {
logV("Now advertising endpoint " + endpointName + " with serviceId " + serviceId);
onAdvertisingStarted(endpointName, serviceId);
}
}
)
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
ApiException apiException = (ApiException) e;
mIsAdvertising = false;
logW("startAdvertising for endpointName "+ endpointName +" serviceId "+ serviceId +" failed.", e);
onAdvertisingStartFailed(endpointName, serviceId, apiException.getStatusCode());
}
}
);
return null;
}
});
}
/** Stops discovery. */
@ReactMethod
public void stopAdvertising(final String serviceId) {
final ConnectionsClient clientSingleton = getConnectionsClientSingleton(serviceId);
logV("Stopping advertising endpoint " + serviceId);
mIsAdvertising = false;
clientSingleton.stopAdvertising();
}
/** Returns {@code true} if currently advertising. */
@ReactMethod
public boolean isAdvertising() {
return mIsAdvertising;
}
@ReactMethod
public void startDiscovering(final String serviceId, final int strategy) {
mIsDiscovering = true;
onDiscoveryStarting(serviceId);
Strategy finalStrategy = Strategy.P2P_CLUSTER;
switch(strategy) {
case 0: finalStrategy = Strategy.P2P_CLUSTER;
break;
case 1: finalStrategy = Strategy.P2P_STAR;
break;
}
final Activity activity = getCurrentActivity();
final ConnectionsClient clientSingleton = getConnectionsClientSingleton(serviceId);
final DiscoveryOptions discoveryOptions = new DiscoveryOptions(finalStrategy);
permissionsCheck(activity, Arrays.asList(getRequiredPermissions()), new Callable<Void>() {
@Override
public Void call() throws Exception {
clientSingleton.startDiscovery(
serviceId,
getEndpointDiscoveryCallback(serviceId),
discoveryOptions
).addOnSuccessListener(
new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unusedResult) {
logV("Now discovering for serviceId "+ serviceId);
onDiscoveryStarted(serviceId);
}
}
).addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
ApiException apiException = (ApiException) e;
mIsDiscovering = false;
logW("startDiscovering for serviceId "+serviceId+" failed.", e);
onDiscoveryStartFailed(serviceId, apiException.getStatusCode());
}
}
);
return null;
}
});
}
/** Stops discovery. */
@ReactMethod
public void stopDiscovering(String serviceId) {
final ConnectionsClient clientSingleton = getConnectionsClientSingleton(serviceId);
logV("Stopping discovering endpoints " + serviceId);
mIsDiscovering = false;
clientSingleton.stopDiscovery();
}
/** Returns {@code true} if currently discovering. */
@ReactMethod
public boolean isDiscovering() {
return mIsDiscovering;
}
/** Returns {@code true} if currently connecting. */
@ReactMethod
public boolean isConnecting() {
return mIsConnecting;
}
/**
* Called when advertising starting
*/
private void onAdvertisingStarting(final String endpointName, final String serviceId) {
// Broadcast endpoint discovered
Intent i = new Intent("com.butchmarshall.reactnative.google.nearby.connection.AdvertisingStarting");
Bundle bundle = new Bundle();
bundle.putString("endpointName", endpointName);
bundle.putString("serviceId", serviceId);
i.putExtras(bundle);
final Activity activity = getCurrentActivity();
activity.sendBroadcast(i);
}
private BroadcastReceiver mAdvertisingStartingReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
String endpointName = intent.getStringExtra("endpointName");
String serviceId = intent.getStringExtra("serviceId");
WritableMap out = Arguments.createMap();
out.putString("endpointName", endpointName);
out.putString("serviceId", serviceId);
sendEvent(getReactApplicationContext(), "advertising_starting", out);
}
}
};
private void unregisterAdvertisingStartingHandler() {
getReactApplicationContext().unregisterReceiver(mAdvertisingStartingReceiver);
}
private void registerAdvertisingStartingHandler() {
IntentFilter intentFilter = new IntentFilter("com.butchmarshall.reactnative.google.nearby.connection.AdvertisingStarting");
getReactApplicationContext().registerReceiver(mAdvertisingStartingReceiver, intentFilter);
}
/**
* Called when advertising started
*/
private void onAdvertisingStarted(final String endpointName, final String serviceId) {
// Broadcast endpoint discovered
Intent i = new Intent("com.butchmarshall.reactnative.google.nearby.connection.AdvertisingStarted");
Bundle bundle = new Bundle();
bundle.putString("endpointName", endpointName);
bundle.putString("serviceId", serviceId);
i.putExtras(bundle);
final Activity activity = getCurrentActivity();
activity.sendBroadcast(i);
}
private BroadcastReceiver mAdvertisingStartedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
String endpointName = intent.getStringExtra("endpointName");
String serviceId = intent.getStringExtra("serviceId");
WritableMap out = Arguments.createMap();
out.putString("endpointName", endpointName);
out.putString("serviceId", serviceId);
sendEvent(getReactApplicationContext(), "advertising_started", out);
}
}
};
private void unregisterAdvertisingStartedHandler() {
getReactApplicationContext().unregisterReceiver(mAdvertisingStartedReceiver);
}
private void registerAdvertisingStartedHandler() {
IntentFilter intentFilter = new IntentFilter("com.butchmarshall.reactnative.google.nearby.connection.AdvertisingStarted");
getReactApplicationContext().registerReceiver(mAdvertisingStartedReceiver, intentFilter);
}
/**
* Called when advertising failed to start
*/
private void onAdvertisingStartFailed(final String endpointName, final String serviceId, final int statusCode) {
// Broadcast endpoint discovered
Intent i = new Intent("com.butchmarshall.reactnative.google.nearby.connection.AdvertisingStartFailed");
Bundle bundle = new Bundle();
bundle.putInt("statusCode", statusCode);
bundle.putString("endpointName", endpointName);
bundle.putString("serviceId", serviceId);
i.putExtras(bundle);
final Activity activity = getCurrentActivity();
activity.sendBroadcast(i);
}
private BroadcastReceiver mAdvertisingStartFailedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
int statusCode = intent.getIntExtra("statusCode", -1);
String endpointName = intent.getStringExtra("endpointName");
String serviceId = intent.getStringExtra("serviceId");
WritableMap out = Arguments.createMap();
out.putInt("statusCode", statusCode);
out.putString("endpointName", endpointName);
out.putString("serviceId", serviceId);
sendEvent(getReactApplicationContext(), "advertising_start_failed", out);
}
}
};
private void unregisterAdvertisingStartFailedHandler() {
getReactApplicationContext().unregisterReceiver(mAdvertisingStartFailedReceiver);
}
private void registerAdvertisingStartFailedHandler() {
IntentFilter intentFilter = new IntentFilter("com.butchmarshall.reactnative.google.nearby.connection.AdvertisingStartFailed");
getReactApplicationContext().registerReceiver(mAdvertisingStartFailedReceiver, intentFilter);
}
/**
* Called when discovery starting
*/
private void onDiscoveryStarting(final String serviceId) {
// Broadcast endpoint discovered
Intent i = new Intent("com.butchmarshall.reactnative.google.nearby.connection.DiscoveryStarting");
Bundle bundle = new Bundle();
bundle.putString("serviceId", serviceId);
i.putExtras(bundle);
final Activity activity = getCurrentActivity();
activity.sendBroadcast(i);
}
private BroadcastReceiver mDiscoveryStartingReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
String serviceId = intent.getStringExtra("serviceId");
WritableMap out = Arguments.createMap();
out.putString("serviceId", serviceId);
sendEvent(getReactApplicationContext(), "discovery_starting", out);
}
}
};
private void unregisterDiscoveryStartingHandler() {
getReactApplicationContext().unregisterReceiver(mDiscoveryStartingReceiver);
}
private void registerDiscoveryStartingHandler() {
IntentFilter intentFilter = new IntentFilter("com.butchmarshall.reactnative.google.nearby.connection.DiscoveryStarting");
getReactApplicationContext().registerReceiver(mDiscoveryStartingReceiver, intentFilter);
}
/**
* Called when discovery started
*/
private void onDiscoveryStarted(final String serviceId) {
// Broadcast endpoint discovered
Intent i = new Intent("com.butchmarshall.reactnative.google.nearby.connection.DiscoveryStarted");
Bundle bundle = new Bundle();
bundle.putString("serviceId", serviceId);
i.putExtras(bundle);
final Activity activity = getCurrentActivity();
activity.sendBroadcast(i);
}
private BroadcastReceiver mDiscoveryStartedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
String serviceId = intent.getStringExtra("serviceId");
WritableMap out = Arguments.createMap();
out.putString("serviceId", serviceId);
sendEvent(getReactApplicationContext(), "discovery_started", out);
}
}
};
private void unregisterDiscoveryStartedHandler() {
getReactApplicationContext().unregisterReceiver(mDiscoveryStartedReceiver);
}
private void registerDiscoveryStartedHandler() {
IntentFilter intentFilter = new IntentFilter("com.butchmarshall.reactnative.google.nearby.connection.DiscoveryStarted");
getReactApplicationContext().registerReceiver(mDiscoveryStartedReceiver, intentFilter);
}
/**
* Called when discovery started
*/
private void onDiscoveryStartFailed(final String serviceId, int statusCode) {
Intent i = new Intent("com.butchmarshall.reactnative.google.nearby.connection.DiscoveryStartFailed");
Bundle bundle = new Bundle();
bundle.putInt("statusCode", statusCode);
bundle.putString("serviceId", serviceId);
i.putExtras(bundle);
final Activity activity = getCurrentActivity();
activity.sendBroadcast(i);
}
private BroadcastReceiver mDiscoveryStartFailedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
int statusCode = intent.getIntExtra("statusCode", -1);
String serviceId = intent.getStringExtra("serviceId");
WritableMap out = Arguments.createMap();
out.putInt("statusCode", statusCode);
out.putString("serviceId", serviceId);
sendEvent(getReactApplicationContext(), "discovery_start_failed", out);
}
}
};
private void unregisterDiscoveryStartFailedHandler() {
getReactApplicationContext().unregisterReceiver(mDiscoveryStartFailedReceiver);
}
private void registerDiscoveryStartFailedHandler() {
IntentFilter intentFilter = new IntentFilter("com.butchmarshall.reactnative.google.nearby.connection.DiscoveryStartFailed");
getReactApplicationContext().registerReceiver(mDiscoveryStartFailedReceiver, intentFilter);
}
/**
* Called when a payload was received
*/
private void onReceivePayload(final String serviceId, final String endpointId, Payload payload) {
int payloadType = payload.getType();
long payloadId = payload.getId();
// Broadcast endpoint discovered
Intent i = new Intent("com.butchmarshall.reactnative.google.nearby.connection.ReceivePayload");
Bundle bundle = new Bundle();
bundle.putString("serviceId", serviceId);
bundle.putString("endpointId", endpointId);
bundle.putInt("payloadType", payloadType);
bundle.putString("payloadId", Long.toString(payloadId));
/*
if (payloadType == Payload.Type.FILE) {
long payloadSize = payload.getSize();
bundle.putLong("payloadSize", payloadSize);
}
*/
i.putExtras(bundle);
final Activity activity = getCurrentActivity();
activity.sendBroadcast(i);
}
private BroadcastReceiver mOnReceivePayloadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
String serviceId = intent.getStringExtra("serviceId");
String endpointId = intent.getStringExtra("endpointId");
int payloadType = intent.getIntExtra("payloadType", -1);
String payloadId = intent.getStringExtra("payloadId");
WritableMap out = Arguments.createMap();
out.putString("serviceId", serviceId);
out.putString("endpointId", endpointId);
out.putInt("payloadType", payloadType);
out.putString("payloadId", payloadId);
if (payloadType == Payload.Type.FILE) {
long payloadSize = intent.getLongExtra("payloadSize", -1);
out.putDouble("payloadSize", payloadSize);
}
sendEvent(getReactApplicationContext(), "receive_payload", out);
}
}
};
private void unregisterOnReceivePayloadHandler() {
getReactApplicationContext().unregisterReceiver(mOnReceivePayloadReceiver);
}
private void registerOnReceivePayloadHandler() {
IntentFilter intentFilter = new IntentFilter("com.butchmarshall.reactnative.google.nearby.connection.ReceivePayload");
getReactApplicationContext().registerReceiver(mOnReceivePayloadReceiver, intentFilter);
}
/**
* Called when there is an update to a payload
*/
private void onPayloadUpdate(final String serviceId, final String endpointId, PayloadTransferUpdate update) {
long bytesTransferred = update.getBytesTransferred();
long totalBytes = update.getTotalBytes();
long payloadId = update.getPayloadId();
int payloadStatus = update.getStatus();
int payloadHashCode = update.hashCode();
// Broadcast endpoint discovered
Intent i = new Intent("com.butchmarshall.reactnative.google.nearby.connection.PayloadUpdate");
Bundle bundle = new Bundle();
bundle.putString("serviceId", serviceId);
bundle.putString("endpointId", endpointId);
bundle.putLong("bytesTransferred", bytesTransferred);
bundle.putLong("totalBytes", totalBytes);
bundle.putString("payloadId", Long.toString(payloadId));
bundle.putInt("payloadStatus", payloadStatus);
bundle.putInt("payloadHashCode", payloadHashCode);
i.putExtras(bundle);
final Activity activity = getCurrentActivity();
activity.sendBroadcast(i);
}
private BroadcastReceiver mRegisterOnPayloadUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
String serviceId = intent.getStringExtra("serviceId");
String endpointId = intent.getStringExtra("endpointId");
long bytesTransferred = intent.getLongExtra("bytesTransferred", -1);
long totalBytes = intent.getLongExtra("totalBytes", -1);
String payloadId = intent.getStringExtra("payloadId");
int payloadStatus = intent.getIntExtra("payloadStatus", -1);
int payloadHashCode = intent.getIntExtra("payloadHashCode", -1);
WritableMap out = Arguments.createMap();
out.putString("serviceId", serviceId);
out.putString("endpointId", endpointId);
out.putDouble("bytesTransferred", bytesTransferred);
out.putDouble("totalBytes", totalBytes);
out.putString("payloadId", payloadId);
out.putInt("payloadStatus", payloadStatus);
out.putInt("payloadHashCode", payloadHashCode);
sendEvent(getReactApplicationContext(), "payload_transfer_update", out);
}
}
};
private void unregisterOnPayloadUpdateHandler() {
getReactApplicationContext().unregisterReceiver(mRegisterOnPayloadUpdateReceiver);
}
private void registerOnPayloadUpdateHandler() {
IntentFilter intentFilter = new IntentFilter("com.butchmarshall.reactnative.google.nearby.connection.PayloadUpdate");
getReactApplicationContext().registerReceiver(mRegisterOnPayloadUpdateReceiver, intentFilter);
}
/**
* Called when sending payload fails
*/
private void onSendPayloadFailed(final String serviceId, final String endpointId, Payload payload, int statusCode) {
int payloadType = payload.getType();
long payloadId = payload.getId();
// Broadcast endpoint discovered
Intent i = new Intent("com.butchmarshall.reactnative.google.nearby.connection.SendPayloadFailed");
Bundle bundle = new Bundle();
bundle.putString("serviceId", serviceId);
bundle.putString("endpointId", endpointId);
bundle.putInt("statusCode", statusCode);
bundle.putInt("payloadType", payloadType);
bundle.putString("payloadId", Long.toString(payloadId));
i.putExtras(bundle);
final Activity activity = getCurrentActivity();
activity.sendBroadcast(i);
}
private BroadcastReceiver mSendPayloadFailedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
String serviceId = intent.getStringExtra("serviceId");
String endpointId = intent.getStringExtra("endpointId");
int statusCode = intent.getIntExtra("statusCode", -1);
int payloadType = intent.getIntExtra("payloadType", -1);
String payloadId = intent.getStringExtra("payloadId");
WritableMap out = Arguments.createMap();
out.putString("serviceId", serviceId);
out.putString("endpointId", endpointId);
out.putInt("statusCode", statusCode);