-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathWebAppInterface.java
More file actions
1378 lines (1194 loc) · 49.7 KB
/
Copy pathWebAppInterface.java
File metadata and controls
1378 lines (1194 loc) · 49.7 KB
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 fr.geolabs.dev.mapmint4me;
import android.*;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.location.GnssStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.util.Patterns;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.widget.EditText;
import android.widget.Toast;
import com.unity3d.player.UnityPlayerActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.math.BigInteger;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import static android.support.v4.content.ContextCompat.startActivity;
public class WebAppInterface {
private boolean mCenter = false;
private Context mContext;
private String errorMsg;
/**
* Instantiate the interface and set the context
*/
WebAppInterface(Context c) {
mContext = c;
}
/**
* Set mTop to true/false from the web page
*/
@JavascriptInterface
public void setToastToCenter(boolean center) {
mCenter = center;
}
/**
* Show a toast from the web page
*/
@JavascriptInterface
public void showToast(String toast) {
Toast ltoast = Toast.makeText(mContext, toast, Toast.LENGTH_LONG);
if (mCenter)
ltoast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
ltoast.show();
}
private NotificationManager mManager;
private int currentId=0;
@JavascriptInterface
public void OnButtonClick()
{
Intent intent = new Intent(mContext, UnityPlayerActivity.class);
try{
mContext.startActivity(intent);
}
catch (Exception e){
}
}
@JavascriptInterface
public void invokeNavigation(String path){
Uri gmmIntentUri = Uri.parse("google.navigation:q="+path);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
mContext.startActivity(mapIntent);
}
/**
* Show a toast from the web page
*/
@JavascriptInterface
public void notify(String msg) {
//mContext.createNotificationChannel();
Intent intent = new Intent(mContext, MapMint4ME.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext, ((MapMint4ME)mContext).CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My notification")
.setContentText(msg)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// Set the intent that will fire when the user taps the notification
//.setContentIntent(pendingIntent);
//.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
currentId++;
notificationManager.notify(currentId, mBuilder.build());
}
@JavascriptInterface
public boolean getInternetStatus() {
return ((MapMint4ME) mContext).isInternetActivated();
}
@JavascriptInterface
public String getFullGPS() throws Exception {
int permissionCheck = ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(((MapMint4ME) mContext), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, MapMint4ME.MY_PERMISSIONS_REQUEST_GPS);
}
boolean hasPosition = false;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
Location location = null; // location
// The minimum distance to change Updates in meters
final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
LocationManager myLocationManager;
myLocationManager = ((MapMint4ME) mContext).getLocationManager();
// getting GPS status
isGPSEnabled = myLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = myLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
String source = null;
JSONArray jsonArray = new JSONArray();
if (isNetworkEnabled) {
myLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, 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) {
}
});
source = "Network";
Log.d("Network", "Network");
if (myLocationManager != null) {
location = myLocationManager
.getLastKnownLocation(myLocationManager.NETWORK_PROVIDER);
hasPosition = true;
JSONObject json = new JSONObject();
if (location != null && hasPosition) {
json.put("lat", location.getLatitude());
json.put("lon", location.getLongitude());
json.put("source", source);
jsonArray.put(jsonArray.length(), json);
}
}
}
if (isGPSEnabled) {
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, 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) {
}
});
Log.d("GPS Enabled", "GPS Enabled");
source = "GPS";
if (myLocationManager != null) {
location = myLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
hasPosition = true;
}
JSONObject json = new JSONObject();
if (location != null && hasPosition) {
json.put("lat", location.getLatitude());
json.put("lon", location.getLongitude());
json.put("source", source);
jsonArray.put(jsonArray.length(), json);
}
}
JSONObject json = new JSONObject();
((MapMint4ME) mContext).startLocationUpdates();
Location location1 = ((MapMint4ME) mContext).getLastLocation();
if (location1 != null) {
json.put("lat", location1.getLatitude());
json.put("lon", location1.getLongitude());
json.put("source", "other");
jsonArray.put(jsonArray.length(), json);
}
return (jsonArray.toString());
}
@RequiresApi(api = Build.VERSION_CODES.N)
@JavascriptInterface
public String getGPS() throws Exception {
int permissionCheck = ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(((MapMint4ME) mContext), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, MapMint4ME.MY_PERMISSIONS_REQUEST_GPS);
}
boolean hasPosition = false;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
Location location = null; // location
// The minimum distance to change Updates in meters
final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
LocationManager myLocationManager;
myLocationManager = ((MapMint4ME) mContext).getLocationManager();
GnssStatus.Callback mGnssStatusCallback = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
mGnssStatusCallback = new GnssStatus.Callback() {
@Override
public void onSatelliteStatusChanged(GnssStatus status) {
int satelliteCount = status.getSatelliteCount();
int usedSatellites = 0;
float totalSnr = 0;
int totalViewedSatellites=0;
for (int i = 0; i < satelliteCount; i++){
if (status.usedInFix(i)) {
usedSatellites++;
totalSnr += status.getCn0DbHz(i); //this method obtains the signal from each satellite
}
totalViewedSatellites++;
}
// we calculate the average of the power of the GPS signal
float avgSnr = (usedSatellites > 0) ? totalSnr / usedSatellites: 0.0f;
Log.d("GNSS", "Number used satelites: " + usedSatellites + " SNR: " + totalSnr+" avg SNR: "+avgSnr+" total viewed satellites: "+totalViewedSatellites);
}
};
}
try {
myLocationManager.registerGnssStatusCallback(mGnssStatusCallback);
Log.e("GNSS","STATUS OK");
} catch (SecurityException e) {
Log.e("GNSS","Error "+e);
}
// getting GPS status
isGPSEnabled = myLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = myLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
String source = null;
if (!isGPSEnabled && !isNetworkEnabled) {
return getGPSMin();// no network provider is enabled
} else {
// First get location from Network Provider
if (!isGPSEnabled && isNetworkEnabled) {
myLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 0, 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) {
}
});
source = "Network";
Log.d("Network", "Network");
if (myLocationManager != null) {
location = myLocationManager
.getLastKnownLocation(myLocationManager.NETWORK_PROVIDER);
hasPosition = true;
}
} else
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null && !hasPosition) {
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 0, 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) {
}
});
Log.d("GPS Enabled", "GPS Enabled");
source = "GPS";
if (myLocationManager != null) {
location = myLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
hasPosition = true;
}else{
myLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 0, 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) {
}
});
source = "Network";
Log.d("Network", "Network");
if (myLocationManager != null) {
location = myLocationManager
.getLastKnownLocation(myLocationManager.NETWORK_PROVIDER);
hasPosition = true;
}
}
}
}
}
JSONObject json = new JSONObject();
if (location != null && hasPosition) {
json.put("lat", location.getLatitude());
json.put("lon", location.getLongitude());
json.put("source", source);
} else {
return getGPSMin();
}
//String tmp=String.valueOf(loc.getLatitude())+","+String.valueOf(loc.getLongitude());
return (json.toString());
}
@JavascriptInterface
public String getGPSMin() throws JSONException {
JSONObject json = new JSONObject();
((MapMint4ME) mContext).startLocationUpdates();
Location location = ((MapMint4ME) mContext).getLastLocation();
if (location != null) {
json.put("lat", location.getLatitude());
json.put("lon", location.getLongitude());
}
json.put("source", "other");
return (json.toString());
}
@JavascriptInterface
public String getLang() throws JSONException {
return Locale.getDefault().getLanguage();
}
@JavascriptInterface
public String getAUID() {
return Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
}
@JavascriptInterface
public String getMailAccount() {
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
int permissionCheck = ContextCompat.checkSelfPermission(((MapMint4ME) mContext), android.Manifest.permission.GET_ACCOUNTS);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(((MapMint4ME) mContext), new String[]{android.Manifest.permission.GET_ACCOUNTS}, MapMint4ME.MY_PERMISSIONS_REQUEST_GPS);
} else {
Account[] accounts = AccountManager.get(mContext).getAccountsByType("com.google");
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
return account.name;
}
}
}
return null;
}
/**
* Set text to the string to be translated
*/
@JavascriptInterface
public String translate(String text) {
try {
return mContext.getString(mContext.getResources().getIdentifier(text, "string", mContext.getPackageName()));
} catch (Exception e) {
return e.toString();
}
}
/**
* Set mTop to true/false from the web page
@JavascriptInterface
public String getOrientation() throws JSONException{
try {
((MapMint4ME)mContext).updateOrientationAngles();
float[] res=((MapMint4ME)mContext).getOrientationAngles();
Log.e("Error", "" + res.toString());
JSONArray jsonArray = new JSONArray();
for(int i=0;i<3;i++)
jsonArray.put(i,res[i]);
float[] res1=((MapMint4ME)mContext).getRotationMatrix();
Log.e("Error", "" + res.toString());
for(int i=0;i<3;i++)
jsonArray.put(i+3,res1[i]);
return jsonArray.toString();
} catch (Exception e) {
Log.e("Error", "" + e.toString());
return e.toString();
}
}*/
private LocalDB db = null;
/**
* Display Table
*/
@JavascriptInterface
public String displayTable(String table, String[] fields) {
// db.close();
if (db == null)
db = new LocalDB(mContext);
return db.getRows(table, fields).toString();
}
/**
* Rebuild chunk
*/
@JavascriptInterface
public String rebuildChunk(String table, String[] fields) {
// db.close();
if (db == null)
db = new LocalDB(mContext);
return db.rebuildChunk(table, fields).toString();
}
/**
* Execute Query
*/
@JavascriptInterface
public long executeQuery(String query, String[] values, int[] types) {
if (db == null)
db = new LocalDB(mContext);
return db.execute(query, values, types);
}
private LocalDB dbs = null;
/**
* Display Table from specific DB
*/
@JavascriptInterface
public String displayTableFromDb(String dbName, String table, String[] fields) {
if (dbs != null)
dbs.close();
dbs = new LocalDB(mContext, dbName);
return dbs.getRows(table, fields);
}
private LocalDB dbt = null;
/**
* Display tiles
*/
@JavascriptInterface
public String displayTile(String xyz) {
if (dbt != null)
dbt.close();
dbt = new LocalDB(mContext, "tiles.db");
return dbt.getTile(xyz);
}
@JavascriptInterface
public String getNBTiles(String[] values, int[] types) {
if (dbt != null)
dbt.close();
dbt = new LocalDB(mContext, "tiles.db");
return dbt.getRows("select count(*) as cnt from (select * from tiles limit 2) as a", values);
}
/**
* Set mTop to true/false from the web page
*/
@JavascriptInterface
public long executeQueryFromDb(String dbName, String query, String[] values, int[] types) {
if (dbs != null)
dbs.close();
dbs = new LocalDB(mContext, dbName);
return dbs.execute(query, values, types);
}
/**
* Set mTop to true/false from the web page
*/
@JavascriptInterface
public void queryCamera(String id, String cid) {
((MapMint4ME) mContext).invokeCamera(id, cid);
}
@JavascriptInterface
public void pickupImage(String id, String cid) {
((MapMint4ME) mContext).invokePickupImage(id, cid);
}
@JavascriptInterface
public int getHeight() {
Display display = ((MapMint4ME) mContext).getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
Log.e("Width", "" + size.x);
Log.e("height", "" + size.y);
return size.y;
}
private String fileSaved=null;
@JavascriptInterface
public void newDownloadFile(final String url) {
fileSaved=null;
new Thread(new Runnable() {
public void run() {
fileSaved=_downloadFile(url,0);
}
}).start();
}
@JavascriptInterface
public String downloadedFile() {
while(fileSaved!=null);
return fileSaved;
}
@JavascriptInterface
public void startWelcomeScreen(){
((MapMint4ME) mContext).launchWelcomeScreen();
((MapMint4ME) mContext).finish();
}
@JavascriptInterface
public void keepScreenOn(){
((MapMint4ME) mContext).runOnUiThread(new Runnable() {
public void run() {
((MapMint4ME) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
});
}
@JavascriptInterface
public void screenCanGoOff(){
((MapMint4ME) mContext).runOnUiThread(new Runnable() {
public void run() {
((MapMint4ME) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
});
}
private class DownloadFilesTask extends AsyncTask<String, Integer, String> {
public int id=0;
protected String doInBackground(String... urls) {
int count = urls.length;
long totalSize = 0;
String res=null;
for (int i = 0; i < count; i++) {
//totalSize += Downloader.downloadFile(urls[i]);
//publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
res=_downloadFile(urls[i],id);
if (isCancelled()) break;
}
return res;
}
public void myProgressPublication(int val){
publishProgress(val);
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
public void setProgressPercent(Integer... progress){
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
private int counter=0;
@JavascriptInterface
public void reinitCounter() {
counter=0;
}
@JavascriptInterface
public String downloadFile(final String url) {
/*DownloadFilesTask myTask = new DownloadFilesTask();
myTask.execute(url);*/
if(url.contains("tiles")) {
File asset_dir = new File(mContext.getFilesDir() + File.separator + "data");
String[] tmp = url.split("/");
final String fileName = asset_dir.getAbsolutePath() + File.separator + tmp[tmp.length - 1];
((MapMint4ME) mContext).beginDownload(url,tmp[tmp.length - 1]);
return "started";
}else
try {
DownloadFilesTask tmp=new DownloadFilesTask();
tmp.id=counter;
tmp.execute(url);
counter+=1;
return "started";
}catch(Exception e) {
return null;
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@JavascriptInterface
public String _downloadFile(String url, final int id) {
File asset_dir = new File(mContext.getFilesDir() + File.separator + "data");
String[] tmp = url.split("/");
final String fileName = asset_dir.getAbsolutePath() + File.separator + tmp[tmp.length - 1];
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext, ((MapMint4ME) mContext).CHANNEL_ID);
mBuilder.setContentTitle(tmp[tmp.length - 1].split("_")[0])
.setContentText(tmp[tmp.length - 1])
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_LOW);
int PROGRESS_MAX = 100;
int PROGRESS_CURRENT = 0;
mBuilder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
currentId++;
notificationManager.notify(currentId, mBuilder.build());
try {
URL mUrl = new URL(url);
URLConnection connection = mUrl.openConnection();
connection.connect();
int fileLenth = connection.getContentLength();
BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
FileOutputStream fos = new FileOutputStream(fileName);
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int x = 0;
int y=0;
int myCnt=0;
Log.w("WebAppInterface", ""+fileLenth);
int lTot=fileLenth/1024;
if(lTot==0)
lTot=1;
while ((x = in.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
myCnt+=x;
if(myCnt==fileLenth || y%15==0){
mBuilder.setContentText((myCnt/(1024*1024))+" / "+(fileLenth/(1024*1024))+" Mb")
.setProgress(PROGRESS_MAX, (y*100)/lTot, false);
notificationManager.notify(currentId, mBuilder.build());
//myTask.myProgressPublication((y*100)/lTot);
}
y++;
}
mBuilder.setContentText("Completed")
.setProgress(PROGRESS_MAX, PROGRESS_MAX, false);
notificationManager.notify(currentId, mBuilder.build());
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
((MapMint4ME) mContext).runOnUiThread(new Runnable() {
public void run() {
String[] tmp = fileName.split("/");
((MapMint4ME)mContext).getMyWebView().loadUrl("javascript:postUpdate('"+tmp[tmp.length - 1]+"',"+id+");");
}
});
return tmp[tmp.length - 1];
} catch (Exception e) {
//return _downloadFile(url,id);
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
final String exceptionAsString = sw.toString();
Log.w("WebAppInterface", exceptionAsString);
mBuilder.setContentTitle("Download Failed")
.setProgress(PROGRESS_MAX,PROGRESS_MAX,false);
notificationManager.notify(currentId, mBuilder.build());
((MapMint4ME) mContext).runOnUiThread(new Runnable() {
public void run() {
String[] tmp = fileName.split("/");
((MapMint4ME)mContext).getMyWebView().loadUrl("javascript:downloadFailed('"+exceptionAsString+"',"+id+");");
}
});
return null;
//showToast("Error: " + exceptionAsString);
}
}
@JavascriptInterface
public void startReportDirection(){
((MapMint4ME)mContext).startReportDirection();
}
@JavascriptInterface
public void stopReportDirection(){
((MapMint4ME)mContext).stopReportDirection();
}
@JavascriptInterface
public String getBaseLayers() throws JSONException, IOException {
File asset_dir = new File(mContext.getFilesDir() + File.separator + "data");
String srcName = asset_dir.getAbsolutePath() + File.separator + "baseLayers.json";
File fin0 = new File(srcName);
if(fin0.exists()) {
FileInputStream fin = new FileInputStream(srcName);
byte[] buffer = new byte[(int)fin0.length()];
int r;
while ((r = fin.read(buffer)) != -1) {
return new String(buffer);
}
}
return null;
}
@JavascriptInterface
public String getGNStatus() throws JSONException {
JSONObject json = new JSONObject();
ConnectivityManager connectivityManager
= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
json.put("net",(activeNetworkInfo!=null&&activeNetworkInfo.isConnected()));
try{
json.put("gps",getFullGPS());
}
catch(Exception e){
Log.d("BUG GPS!", e.toString());
}
return json.toString();
}
@JavascriptInterface
public boolean getTilesDownloadStatus() {
return ((MapMint4ME)mContext).getDownloadStatus();
}
@SuppressLint("LongLogTag")
@JavascriptInterface
public boolean copyFile(String src,String dest) {
File asset_dir = new File(mContext.getFilesDir() + File.separator + "data");
String srcName = asset_dir.getAbsolutePath() + File.separator + src;
String destName = asset_dir.getAbsolutePath() + File.separator + dest;
/*try {
mContext.deleteDatabase(dest);
}catch(Exception e) {
Log.d("Unable to delete database!", e.toString());
}*/
FileInputStream fin = null;
try {
fin = new FileInputStream(srcName);
FileOutputStream fos = new FileOutputStream(destName);
byte[] buffer = new byte[1024];
int read;
while ((read = fin.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
fin.close();
File srcFile= new File(srcName);
srcFile.delete();
fos.flush();
fos.close();
fos = null;
return true;
} catch (Exception e) {
Log.d("Unable to copy file database!", e.toString());
e.printStackTrace();
return false;
}
}
@JavascriptInterface
public void refreshDbs() {
if (dbs != null)
dbs.close();
dbs=null;
if (db != null)
db.close();
db=null;
}
@SuppressLint("LongLogTag")
public boolean copyFileA(String src, String dest) {
File asset_dir = new File(mContext.getFilesDir() + File.separator + "data");
String srcName = mContext.getExternalFilesDir(null).getAbsolutePath() + File.separator + src;
String destName = asset_dir.getAbsolutePath() + File.separator + dest;
/*try {
mContext.deleteDatabase(dest);
}catch(Exception e) {
Log.d("Unable to delete database!", e.toString());
}*/
FileInputStream fin = null;
try {
if(dbt!=null)
dbt.close();
fin = new FileInputStream(srcName);
FileOutputStream fos = new FileOutputStream(destName);
byte[] buffer = new byte[1024];
int read;
while ((read = fin.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
fin.close();
File srcFile= new File(srcName);
srcFile.delete();
fos.flush();
fos.close();
fos = null;
dbt=null;
Log.d("Copy file database","success");
return true;
} catch (Exception e) {
Log.d("Unable to copy file database!", e.toString());
e.printStackTrace();
return false;
}
}
@JavascriptInterface
public Integer getCurrentAndroidOSersion(){
return android.os.Build.VERSION.SDK_INT;
}
@JavascriptInterface
public String getErrorMsg(){
return errorMsg;
}
/*
@JavascriptInterface
public String uploadFile(final String url,final String field,final String file) {
try {
return new UploadFilesTask().execute(url,field,file).get();
}catch(Exception e) {
return null;
}
}*/
@TargetApi(Build.VERSION_CODES.KITKAT)
@JavascriptInterface
public long getSizeOfFile(String path) {
try {
String fpath = mContext.getFilesDir() + File.separator + "data" + File.separator + path;
File tmpFile = new File(fpath);
return (tmpFile.length()/1024)/1024;
}catch (Exception e) {
return 0;
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@JavascriptInterface
public int SplitFile(String path)
{
try {
File asset_dir = new File(mContext.getFilesDir() + File.separator + "data");
String fpath = mContext.getFilesDir()+File.separator+"data"+ File.separator + path;
//final long sourceSize = Files.size(Paths.get(fpath));
int size;
size = 1638400;
Log.w("Splited 0: ", fpath);
File f = new File(fpath);