-
Notifications
You must be signed in to change notification settings - Fork 184
/
WikitudePlugin.java
926 lines (771 loc) · 30.9 KB
/
WikitudePlugin.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
package com.wikitude.phonegap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.text.format.DateUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.wikitude.architect.ArchitectView;
import com.wikitude.architect.ArchitectView.ArchitectUrlListener;
import com.wikitude.architect.ArchitectView.CaptureScreenCallback;
import com.wikitude.architect.StartupConfiguration;
import com.wikitude.architect.StartupConfiguration.CameraPosition;
import com.wikitude.phonegap.WikitudePlugin.ArchitectViewPhoneGap.OnKeyUpDownListener;
/**
* Basic PhoneGap Wikitude ARchitect Plugin
*
* You must add "<plugin name="WikitudePlugin" value="com.wikitude.phonegap.WikitudePlugin"/>"
* in config.xml to enable this plug-in in your project
*
* Also ensure to have wikitudesdk.jar in your libs folder
*
* Note:
* This plug-in is written under Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0.html
*/
public class WikitudePlugin extends CordovaPlugin implements ArchitectUrlListener {
/** PhoneGap-root to Android-app-assets folder ; e.g. use "assets/foo.html" as source if you want to load foo.html from your android-project's assets-folder */
private static final String LOCAL_ASSETS_PATH_ROOT = "assets/";
/* static action strings */
/**
* opens architect-view (add to view stack)
*/
private static final String ACTION_OPEN = "open";
/**
* closes architect-view (remove view stack)
*/
private static final String ACTION_CLOSE = "close";
/**
* set visibility of architectView to visible (of present)
*/
private static final String ACTION_SHOW = "show";
/**
* set visibility of architectView to invisible (of present)
*/
private static final String ACTION_HIDE = "hide";
/**
* inject location information
*/
private static final String ACTION_SET_LOCATION = "setLocation";
/**
* inject location information
*/
private static final String ACTION_CAPTURE_SCREEN = "captureScreen";
/**
* callback for uri-invocations
*/
private static final String ACTION_ON_URLINVOKE = "onUrlInvoke";
/**
* life-cycle notification for resume
*/
private static final String ACTION_ON_RESUME = "onResume";
/**
* life-cycle notification for pause
*/
private static final String ACTION_ON_PAUSE = "onPause";
/**
* check if view is on view-stack (no matter if visible or not)
*/
private static final String ACTION_STATE_ISOPEN = "isOpen";
/**
* opens architect-view (add to view stack)
*/
private static final String ACTION_IS_DEVICE_SUPPORTED = "isDeviceSupported";
/**
* check if view is on view-stack (no matter if visible or not)
*/
private static final String ACTION_CALL_JAVASCRIPT = "callJavascript";
/**
* the Wikitude ARchitectview
*/
private ArchitectViewPhoneGap architectView;
/**
* callback-Id of url-invocation method
*/
private CallbackContext urlInvokeCallback = null;
/**
* callback-id of "open"-action method
*/
private CallbackContext openCallback = null;
/**
* last known location of the user, used internally for content-loading after user location was fetched
*/
protected Location lastKnownLocaton;
/**
* sample location strategy
*/
protected ILocationProvider locationProvider;
/**
* location listener receives location updates and must forward them to the architectView
*/
protected LocationListener locationListener;
private boolean useCustomLocation = false;
@Override
public boolean execute( final String action, final JSONArray args, final CallbackContext callContext ) {
/* hide architect-view -> destroy and remove from activity */
if ( WikitudePlugin.ACTION_CLOSE.equals( action ) ) {
if ( this.architectView != null ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
removeArchitectView();
}
} );
callContext.success( action + ": architectView is present" );
}
else {
callContext.error( action + ": architectView is not present" );
}
return true;
}
/* return success only if view is opened (no matter if visible or not) */
if ( WikitudePlugin.ACTION_STATE_ISOPEN.equals( action ) ) {
if ( this.architectView != null ) {
callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
return true;
}
/* return success only if view is opened (no matter if visible or not) */
if ( WikitudePlugin.ACTION_IS_DEVICE_SUPPORTED.equals( action ) ) {
JSONArray jsonArray = null;
try {
jsonArray = args.getJSONArray( 0 );
} catch (JSONException e) {
}
int featuresBitMap = convertArFeatures(jsonArray);
if ( (ArchitectView.getSupportedFeaturesForDevice( this.cordova.getActivity() ) & featuresBitMap) == featuresBitMap ) {
callContext.success("This device is supported" );
} else {
callContext.error("This device is NOT supported" );
}
return true;
}
if (WikitudePlugin.ACTION_CAPTURE_SCREEN.equals(action) ) {
if (architectView!=null) {
int captureMode = ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM_AND_WEBVIEW;
try {
captureMode = ( args.getBoolean( 0 )) ? ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM_AND_WEBVIEW : ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM;
} catch (Exception e) {
// unexpected error;
}
String name = "";
if (args.length() > 1 && !args.isNull(1)) {
try {
name = args.getString(1);
} catch (final Exception e) {
e.printStackTrace();
}
}
final String fileName = name;
architectView.captureScreen(captureMode, new CaptureScreenCallback() {
@Override
public void onScreenCaptured(Bitmap screenCapture) {
final File screenCaptureFile;
final String name = System.currentTimeMillis() + ".jpg";
try {
if (fileName.equals("")) {
final File imageDirectory = Environment.getExternalStorageDirectory();
if (imageDirectory == null) {
callContext.error("External storage not available");
}
screenCaptureFile = new File (imageDirectory, name);
} else {
File screenCapturePath = new File (fileName);
if (screenCapturePath.isDirectory()) {
screenCaptureFile = new File (screenCapturePath, name);
} else {
screenCaptureFile = screenCapturePath;
}
}
if (screenCaptureFile.exists()) {
screenCaptureFile.delete();
}
final FileOutputStream out = new FileOutputStream(screenCaptureFile);
screenCapture.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, screenCaptureFile.getAbsolutePath());
Context context= cordova.getActivity().getApplicationContext();
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final String absoluteCaptureImagePath = screenCaptureFile.getAbsolutePath();
callContext.success(absoluteCaptureImagePath);
// in case you want to sent the pic to other applications, uncomment these lines (for future use)
// final Intent share = new Intent(Intent.ACTION_SEND);
// share.setType("image/jpg");
// share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(screenCaptureFile));
// final String chooserTitle = "Share Snaphot";
// cordova.getActivity().startActivity(Intent.createChooser(share, chooserTitle));
}
});
} catch (Exception e) {
callContext.error(e.getMessage());
}
}
});
return true;
}
}
/* life-cycle's RESUME */
if ( WikitudePlugin.ACTION_ON_RESUME.equals( action ) ) {
if ( this.architectView != null ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
WikitudePlugin.this.architectView.onResume();
callContext.success( action + ": architectView is present" );
if (locationProvider != null) {
locationProvider.onResume();
}
}
} );
// callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
return true;
}
/* life-cycle's PAUSE */
if ( WikitudePlugin.ACTION_ON_PAUSE.equals( action ) ) {
if ( architectView != null ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
WikitudePlugin.this.architectView.onPause();
if (locationProvider != null) {
locationProvider.onPause();
}
}
} );
callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
return true;
}
/* set visibility to "visible", return error if view is null */
if ( WikitudePlugin.ACTION_SHOW.equals( action ) ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
if ( architectView != null ) {
architectView.setVisibility( View.VISIBLE );
callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
}
} );
return true;
}
/* set visibility to "invisible", return error if view is null */
if ( WikitudePlugin.ACTION_HIDE.equals( action ) ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
if ( architectView != null ) {
architectView.setVisibility( View.INVISIBLE );
callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
}
} );
return true;
}
/* define call-back for url-invocations */
if ( WikitudePlugin.ACTION_ON_URLINVOKE.equals( action ) ) {
this.urlInvokeCallback = callContext;
final PluginResult result = new PluginResult( PluginResult.Status.NO_RESULT, action + ": registered callback" );
result.setKeepCallback( true );
callContext.sendPluginResult( result );
return true;
}
/* location update */
if ( WikitudePlugin.ACTION_SET_LOCATION.equals( action ) ) {
if ( this.architectView != null ) {
try {
final double lat = args.getDouble( 0 );
final double lon = args.getDouble( 1 );
float alt = Float.MIN_VALUE;
try {
alt = (float)args.getDouble( 2 );
} catch ( Exception e ) {
// invalid altitude -> ignore it
}
final float altitude = alt;
Double acc = null;
try {
acc = args.getDouble( 3 );
} catch ( Exception e ) {
// invalid accuracy -> ignore it
}
final Double accuracy = acc;
if ( this.cordova != null && this.cordova.getActivity() != null ) {
this.useCustomLocation = true;
cordova.getActivity().runOnUiThread(
// this.cordova.getThreadPool().execute(
new Runnable() {
@Override
public void run() {
if ( accuracy != null ) {
WikitudePlugin.this.architectView.setLocation( lat, lon, altitude, accuracy.floatValue() );
} else {
WikitudePlugin.this.architectView.setLocation( lat, lon, altitude );
}
}
} );
}
} catch ( Exception e ) {
callContext.error( action + ": exception thrown, " + e != null ? e.getMessage() : "(exception is NULL)" );
return true;
}
callContext.success( action + ": updated location" );
return true;
} else {
/* return error if there is no architect-view active*/
callContext.error( action + ": architectView is not present" );
}
return true;
}
if ( WikitudePlugin.ACTION_CALL_JAVASCRIPT.equals( action ) ) {
String logMsg = null;
try {
final String callJS = args.getString( 0 );
logMsg = callJS;
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
if ( architectView != null ) {
WikitudePlugin.this.architectView.callJavascript( callJS );
} else {
callContext.error( action + ": architectView is not present" );
}
}
} );
} catch ( JSONException je ) {
callContext.error( action + ": exception thrown, " + je != null ? je.getMessage() : "(exception is NULL)" );
return true;
}
callContext.success( action + ": called js, '" + logMsg + "'" );
return true;
}
/* initial set-up, show ArchitectView full-screen in current screen/activity */
if ( WikitudePlugin.ACTION_OPEN.equals( action ) ) {
this.openCallback = callContext;
PluginResult result = null;
try {
final JSONObject params = args.getJSONObject( 0 );
final String apiKey = params.getString( "SDKKey" );
final String filePath = params.getString( "ARchitectWorldURL" );
int featuresTmp = 0;
try {
final JSONArray jsonArray = params.getJSONArray( "RequiredFeatures" );
featuresTmp = convertArFeatures(jsonArray);
} catch (JSONException e) {
featuresTmp = StartupConfiguration.Features.Geo | StartupConfiguration.Features.Tracking2D;
}
final int features = featuresTmp;
JSONObject startupConfigurationTmp;
try {
startupConfigurationTmp = params.getJSONObject( "StartupConfiguration" );
} catch (Exception e) {
startupConfigurationTmp = null;
}
final JSONObject startupConfiguration = startupConfigurationTmp;
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
try {
WikitudePlugin.this.addArchitectView( apiKey, filePath, features, startupConfiguration );
/* call success method once architectView was added successfully */
if ( openCallback != null ) {
PluginResult result = new PluginResult( PluginResult.Status.OK );
result.setKeepCallback( false );
openCallback.sendPluginResult( result );
}
} catch ( Exception e ) {
/* in case "addArchitectView" threw an exception -> notify callback method asynchronously */
openCallback.error( e != null ? e.getMessage() : "Exception is 'null'" );
}
}
} );
} catch ( Exception e ) {
result = new PluginResult( PluginResult.Status.ERROR, action + ": exception thown, " + e != null ? e.getMessage() : "(exception is NULL)" );
result.setKeepCallback( false );
callContext.sendPluginResult( result );
return true;
}
/* adding architect-view is done in separate thread, ensure to setKeepCallback so one can call success-method properly later on */
result = new PluginResult( PluginResult.Status.NO_RESULT, action + ": no result required, just registered callback-method" );
result.setKeepCallback( true );
callContext.sendPluginResult( result );
return true;
}
/* fall-back return value */
callContext.sendPluginResult( new PluginResult( PluginResult.Status.ERROR, "no such action: " + action ) );
return false;
}
/**
* called when url was invoked in architectView (by e.g. calling document.location = "myprotocoll://foo";
* @param url the invoked url (e.g. "architectsdk://foo")
* @return true if call was handled properly
*/
@Override
public boolean urlWasInvoked( final String url ) {
/* call callback-method if set*/
if ( this.urlInvokeCallback != null ) {
try {
/* pass called url as String to callback-method */
final PluginResult res = new PluginResult( PluginResult.Status.OK, url );
res.setKeepCallback( true );
this.urlInvokeCallback.sendPluginResult( res );
} catch ( Exception e ) {
this.urlInvokeCallback.error( "invalid url invoked: " + url );
}
return true;
}
return false;
}
/**
* hides/removes ARchitect-View completely
* @return true if successful, false otherwise
*/
private boolean removeArchitectView() {
if ( this.architectView != null ) {
/* fake life-cycle calls, because activity is already up and running */
this.architectView.onPause();
this.architectView.onDestroy();
// clean-up used temp-directory
try {
WikitudePlugin.clearCacheFolder( new File( ArchitectView.getCacheDirectoryAbsoluteFilePath( this.cordova.getActivity() ) ), 0 );
} catch ( Exception e ) {
// had troubles in clearing files from cache
e.printStackTrace();
}
this.architectView.setVisibility( View.GONE );
((ViewManager)this.architectView.getParent()).removeView( this.architectView );
this.architectView = null;
WikitudePlugin.handleResumeInCordovaWebView(cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content));
return true;
}
return false;
}
private static int clearCacheFolder( final File dir, final int numDays ) {
int deletedFiles = 0;
if ( dir != null && dir.isDirectory() ) {
try {
for ( File child : dir.listFiles() ) {
//first delete subdirectories recursively
if ( child.isDirectory() ) {
deletedFiles += clearCacheFolder( child, numDays );
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if ( child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS ) {
if ( child.delete() ) {
deletedFiles++;
}
}
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
return deletedFiles;
}
private int convertArFeatures(JSONArray jsonArray) {
int featuresBitMap = 0;
for (int i = 0; i < jsonArray.length(); i++) {
String feature = "";
try {
feature = (String) jsonArray.get(0);
} catch (JSONException e) {
}
if (feature.equalsIgnoreCase("2d_tracking")) {
featuresBitMap = featuresBitMap | StartupConfiguration.Features.Tracking2D;
} else if (feature.equalsIgnoreCase("geo")) {
featuresBitMap = featuresBitMap | StartupConfiguration.Features.Geo;
}
}
if (featuresBitMap == 0) {
featuresBitMap = StartupConfiguration.Features.Tracking2D | StartupConfiguration.Features.Geo;
}
return featuresBitMap;
}
/**
* Architect-Configuration required for proper set-up
* @param apiKey
* @param features
* @return
*/
protected StartupConfiguration getStartupConfiguration( final String apiKey, int features, JSONObject startupConfiguration ) {
StartupConfiguration.CameraPosition cameraPosition = CameraPosition.DEFAULT;
try {
if (startupConfiguration != null) {
if (startupConfiguration.getString("camera_position").compareToIgnoreCase("front") == 0) {
cameraPosition = StartupConfiguration.CameraPosition.FRONT;
} else if (startupConfiguration.getString("camera_position").compareToIgnoreCase("back") == 0) {
cameraPosition = StartupConfiguration.CameraPosition.BACK;
}
}
} catch (JSONException e) {
}
/* no special set-up required in default Wikitude-Plugin, further things required in advanced usage (e.g. Vuforia Image Recognition) */
StartupConfiguration config = new StartupConfiguration( apiKey, features, cameraPosition);
config.setOrigin( StartupConfiguration.ORIGIN_PHONEGAP );
return config;
}
/**
* add architectView to current screen
* @param apiKey developers's api key to use (hides watermarking/intro-animation if it matches your package-name)
* @param filePath the url (starting with http:// for online use; starting with LOCAL_ASSETS_PATH_ROOT if oyu want to load assets within your app-assets folder)
* @param features Augmented Reality mode ()
* @throws IOException might be thrown from ARchitect-SDK
*/
private void addArchitectView( final String apiKey, String filePath, int features, JSONObject startupConfiguration) throws IOException {
if ( this.architectView == null ) {
WikitudePlugin.releaseFocusInCordovaWebView(cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content));
this.architectView = new ArchitectViewPhoneGap( this.cordova.getActivity() , new OnKeyUpDownListener() {
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (architectView!=null && keyCode == KeyEvent.KEYCODE_BACK) {
if (WikitudePlugin.this.locationProvider != null) {
WikitudePlugin.this.locationProvider.onPause();
}
removeArchitectView();
return true;
} else {
return false;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return architectView!=null && keyCode == KeyEvent.KEYCODE_BACK;
}
});
this.architectView.setFocusableInTouchMode(true);
this.architectView.requestFocus();
this.locationListener = new LocationListener() {
@Override
public void onStatusChanged( String provider, int status, Bundle extras ) {
}
@Override
public void onProviderEnabled( String provider ) {
}
@Override
public void onProviderDisabled( String provider ) {
}
@Override
public void onLocationChanged( final Location location ) {
if (location!=null && !WikitudePlugin.this.useCustomLocation) {
WikitudePlugin.this.lastKnownLocaton = location;
if ( WikitudePlugin.this.architectView != null ) {
if ( location.hasAltitude() ) {
WikitudePlugin.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy() );
} else {
WikitudePlugin.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.getAccuracy() );
}
}
}
}
};
/* add content view and fake initial life-cycle */
(this.cordova.getActivity()).addContentView( this.architectView, new ViewGroup.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) );
(this.cordova.getActivity()).setVolumeControlStream( AudioManager.STREAM_MUSIC );
/* fake life-cycle calls, because activity is already up and running */
this.architectView.onCreate( getStartupConfiguration( apiKey, features, startupConfiguration ) );
this.architectView.onPostCreate();
/* register self as url listener to fwd these native calls to PhoneGap */
this.architectView.registerUrlListener( WikitudePlugin.this );
/* load asset from local directory if prefix is used */
if ( filePath.startsWith( WikitudePlugin.LOCAL_ASSETS_PATH_ROOT ) ) {
filePath = filePath.substring( WikitudePlugin.LOCAL_ASSETS_PATH_ROOT.length() );
}
this.architectView.load( filePath );
/* also a fake-life-cycle call (the last one before it is really shown in UI */
this.architectView.onResume();
if ((features & StartupConfiguration.Features.Geo) == features) {
this.locationProvider = new LocationProvider( this.cordova.getActivity(), this.locationListener );
this.locationProvider.onResume();
}
}
// hide keyboard when adding AR view on top of views
InputMethodManager inputManager = (InputMethodManager)
(this.cordova.getActivity()).getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow((this.cordova.getActivity()).getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private static void releaseFocusInCordovaWebView(View rootView) {
if (rootView instanceof CordovaWebView) {
((CordovaWebView)rootView).clearFocus();
}
else if (rootView instanceof ViewGroup) {
final int childCount = ((ViewGroup)rootView).getChildCount();
for (int i=0; i< childCount; i++) {
WikitudePlugin.releaseFocusInCordovaWebView(((ViewGroup)rootView).getChildAt(i));
}
}
}
/**
* To avoid JavaScript in Cordova staying paused after CordovaWebView lost focus call "handleResume" of the CordovaView in current Activity
* @param rootView the root view to search recursively for a CordovaWebView
*/
private static void handleResumeInCordovaWebView(final View rootView) {
if (rootView instanceof CordovaWebView) {
((CordovaWebView)rootView).handleResume(true, true);
((CordovaWebView)rootView).clearFocus();
((CordovaWebView)rootView).requestFocus();
}
else if (rootView instanceof ViewGroup) {
final int childCount = ((ViewGroup)rootView).getChildCount();
for (int i=0; i< childCount; i++) {
WikitudePlugin.handleResumeInCordovaWebView(((ViewGroup)rootView).getChildAt(i));
}
}
}
protected static class ArchitectViewPhoneGap extends ArchitectView{
public static interface OnKeyUpDownListener {
public boolean onKeyDown(int keyCode, KeyEvent event);
public boolean onKeyUp(int keyCode, KeyEvent event);
}
private final OnKeyUpDownListener onKeyUpDownListener;
@Deprecated
public ArchitectViewPhoneGap(Context context) {
super(context);
this.onKeyUpDownListener = null;
}
public ArchitectViewPhoneGap(Context context, OnKeyUpDownListener onKeyUpDownListener) {
super(context);
this.onKeyUpDownListener = onKeyUpDownListener;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// forward onKeyDown events to listener
return this.onKeyUpDownListener!=null && this.onKeyUpDownListener.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// forward onKeyUp events to listener
return this.onKeyUpDownListener!=null && this.onKeyUpDownListener.onKeyUp(keyCode, event);
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction,
Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
// ensure architectView does not loose focus on screen orientation changes etc.
if (!gainFocus) {
this.requestFocus();
}
}
}
/**
* Sample implementation of a locationProvider, feel free to polish this very basic approach (compare http://goo.gl/pvkXV )
* @author Wikitude GmbH
*
*/
private static class LocationProvider implements ILocationProvider {
/** location listener called on each location update */
private final LocationListener locationListener;
/** system's locationManager allowing access to GPS / Network position */
private final LocationManager locationManager;
/** location updates should fire approximately every second */
private static final int LOCATION_UPDATE_MIN_TIME_GPS = 1000;
/** location updates should fire, even if last signal is same than current one (0m distance to last location is OK) */
private static final int LOCATION_UPDATE_DISTANCE_GPS = 0;
/** location updates should fire approximately every second */
private static final int LOCATION_UPDATE_MIN_TIME_NW = 1000;
/** location updates should fire, even if last signal is same than current one (0m distance to last location is OK) */
private static final int LOCATION_UPDATE_DISTANCE_NW = 0;
/** to faster access location, even use 10 minute old locations on start-up */
private static final int LOCATION_OUTDATED_WHEN_OLDER_MS = 1000 * 60 * 10;
/** is gpsProvider and networkProvider enabled in system settings */
private boolean gpsProviderEnabled, networkProviderEnabled;
/** the context in which we're running */
private final Context context;
public LocationProvider( final Context context, LocationListener locationListener ) {
super();
this.locationManager = (LocationManager)context.getSystemService( Context.LOCATION_SERVICE );
this.locationListener = locationListener;
this.context = context;
this.gpsProviderEnabled = this.locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER );
this.networkProviderEnabled = this.locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER );
}
@Override
public void onPause() {
if ( this.locationListener != null && this.locationManager != null && (this.gpsProviderEnabled || this.networkProviderEnabled) ) {
this.locationManager.removeUpdates( this.locationListener );
}
}
@Override
public void onResume() {
if ( this.locationManager != null && this.locationListener != null ) {
// check which providers are available are available
this.gpsProviderEnabled = this.locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER );
this.networkProviderEnabled = this.locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER );
/** is GPS provider enabled? */
if ( this.gpsProviderEnabled ) {
final Location lastKnownGPSLocation = this.locationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER );
if ( lastKnownGPSLocation != null && lastKnownGPSLocation.getTime() > System.currentTimeMillis() - LOCATION_OUTDATED_WHEN_OLDER_MS ) {
locationListener.onLocationChanged( lastKnownGPSLocation );
}
this.locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_UPDATE_MIN_TIME_GPS, LOCATION_UPDATE_DISTANCE_GPS, this.locationListener );
}
/** is Network / WiFi positioning provider available? */
if ( this.networkProviderEnabled ) {
final Location lastKnownNWLocation = this.locationManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER );
if ( lastKnownNWLocation != null && lastKnownNWLocation.getTime() > System.currentTimeMillis() - LOCATION_OUTDATED_WHEN_OLDER_MS ) {
locationListener.onLocationChanged( lastKnownNWLocation );
}
this.locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_MIN_TIME_NW, LOCATION_UPDATE_DISTANCE_NW, this.locationListener );
}
/** user didn't check a single positioning in the location settings, recommended: handle this event properly in your app, e.g. forward user directly to location-settings, new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS ) */
if ( !this.gpsProviderEnabled && !this.networkProviderEnabled ) {
Toast.makeText( this.context, "Please enable GPS and Network positioning in your Settings ", Toast.LENGTH_LONG ).show();
}
}
}
}
private interface ILocationProvider {
/**
* Call when host-activity is resumed (usually within systems life-cycle method)
*/
public void onResume();
/**
* Call when host-activity is paused (usually within systems life-cycle method)
*/
public void onPause();
}
}