-
Notifications
You must be signed in to change notification settings - Fork 3
/
MapsActivity.java
971 lines (879 loc) · 41.3 KB
/
MapsActivity.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
package com.restart.spacestationtracker;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.RequestConfiguration;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.ump.ConsentForm;
import com.google.android.ump.ConsentInformation;
import com.google.android.ump.ConsentRequestParameters;
import com.google.android.ump.UserMessagingPlatform;
import com.nightonke.boommenu.BoomButtons.ButtonPlaceEnum;
import com.nightonke.boommenu.BoomButtons.HamButton;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.ButtonEnum;
import com.nightonke.boommenu.Piece.PiecePlaceEnum;
import com.wooplr.spotlight.SpotlightView;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Contains the google map and uses volley to grab JSON objects and display
* the position of the ISS as a customized marker on the map and update it occasionally.
*/
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener {
public static final String CHANNEL_ID = "iss_notification"; // Notification for Android 8.0 and higher
private static final String TAG = ".MapsActivity"; // Used for volley and occasional Log
private final AtomicBoolean isMobileAdsInitializeCalled = new AtomicBoolean(false);
private ConsentInformation consentInformation; // Need privacy consent before showing ads
private SharedPreferences mSharedPreferences; // Managing options from Settings
private BoomMenuButton mBoomMenu; // Manages the drawer pop menu
private InterstitialAd mInterstitialAd; // Managing interstitial ads with AdMob sdk
private MarkerOptions mMarkerOptions; // Marker options, uses ISS drawable
private DecimalFormat mDecimalFormat; // For number decimal places
private RequestQueue mRequestQueue; // Volley for JSONObject/JSONArray requests
private GoogleMap mMap; // Google maps
private Polyline[] mPolyArray; // An array of polyline. Need 200 for a nice curve
private TextView mDescription; // A description of additional ISS info. Optional
private TextView mLatLong; // Lat & Lon of ISS
private Polyline mPolyLine; // A single poly to help compare any changes from settings
private Context mContext; // Application context
private Marker mMarker; // Marker representing ISS that moves alone the prediction line
private AdView mAdView; // Optional ads
private LatLng mLast; // Used for connecting polyline.
private Timer mPolyTimer; // Updates the poly lines
private Timer mTimer; // Updates map based on refresh rate
private int mInterstitialAdActivity; // Keeps tracks of what activity was requested to open but was paused for ad
private int mPolyCounter; // Counts how many polyline there are
private int mCurrentColor; // Holds the current colors of polylines
private int mCurrentWidth; // Holds the current width of polylines
private int mRefreshRate; // Millisecond between each timer repeat of updating ISS's location
private int mSuccess; // Tracks # times server failed to respond
private int mPoly; // Used for adding on to a timestamp and getting future locations
private int mProgress; // Progress on polylines, make sure we finish one before moving on to next
private boolean mThreadManager; // Checks if polyLines are already being created.
private boolean mFirstTime; // Menu Tutorial
private boolean mStart; // Opened app or returned to activity?
private boolean mOnce; // Move map to ISS's location on start
/**
* When the application begins try to read from SharedPreferences to get ready. Run first
* time setups if needed.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
initializeVariables();
initiateBoomMenu();
if (!mSharedPreferences.getBoolean(getString(R.string.firstTime), true)) {
initializeConsent();
if (consentInformation.canRequestAds()) {
initializeAds();
}
}
}
private void initializeConsent() {
ConsentRequestParameters params = new ConsentRequestParameters.Builder()
.setTagForUnderAgeOfConsent(false)
.build();
consentInformation = UserMessagingPlatform.getConsentInformation(this);
consentInformation.requestConsentInfoUpdate(
this,
params,
(ConsentInformation.OnConsentInfoUpdateSuccessListener) () -> {
UserMessagingPlatform.loadAndShowConsentFormIfRequired(
this,
(ConsentForm.OnConsentFormDismissedListener) loadAndShowError -> {
if (loadAndShowError != null) {
// Consent gathering failed.
// TODO: Report
}
if (consentInformation.canRequestAds()) {
initializeAds();
}
}
);
},
(ConsentInformation.OnConsentInfoUpdateFailureListener) requestConsentError -> {
// Consent gathering failed.
// TODO: Report
});
if (consentInformation.canRequestAds()) {
initializeAds();
}
}
/**
* Create the NotificationChannel, but only on API 26+ because the NotificationChannel class
* is new and not in the support library
* <p>
* Removed until push notification is back on
*/
private void initializeNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.notificationTitle);
String description = getString(R.string.notificationSummary);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null)
notificationManager.createNotificationChannel(channel);
}
}
/**
* Initiate all variables when the activity is started for the first time
*/
private void initializeVariables() {
MapsInitializer.initialize(getApplicationContext());
// Title on the action bar next to the BoomMenu drawer which we will initialize later
ActionBar mActionBar = getSupportActionBar();
assert mActionBar != null;
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
@SuppressLint("InflateParams") View actionBar = mInflater.inflate(R.layout.custom_actionbar, null);
final TextView mTitleTextView = actionBar.findViewById(R.id.title_text);
mTitleTextView.setText(R.string.map_activity);
mActionBar.setCustomView(actionBar);
mActionBar.setDisplayShowCustomEnabled(true);
((Toolbar) actionBar.getParent()).setContentInsetsAbsolute(0, 0);
// Other variables to make the activity start and function
mPoly = 0;
mOnce = true;
mAdView = null;
mStart = false;
mPolyCounter = 0;
mPolyArray = new Polyline[200];
mContext = getApplicationContext();
mRequestQueue = Volley.newRequestQueue(this);
mLatLong = findViewById(R.id.textView);
mDescription = findViewById(R.id.textView2);
PreferenceManager.setDefaultValues(this, R.xml.app_preferences, false);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mRefreshRate = 1000 * (mSharedPreferences.getInt("refresh_Rate", 9) + 1);
mFirstTime = mSharedPreferences.getBoolean(getString(R.string.firstTime), true);
// Animation process for first time users. Skip if not first time (mFirstTime)
final Activity activity = this;
// When view is shown, start our animations for first time users
mLatLong.post(() -> {
if (mFirstTime) {
startAnimation(mTitleTextView, activity);
}
});
}
/**
* Initialize ads when the activity is started for the first time
*/
private void initializeAds() {
if (isMobileAdsInitializeCalled.getAndSet(true)) {
return;
}
List<String> testDevices = new ArrayList<>();
//testDevices.add("54686107F6B785A3B1575E1F6E4BD613");
MobileAds.setRequestConfiguration(new RequestConfiguration.Builder()
.setTestDeviceIds(testDevices)
.build());
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) {
mapFragment.getMapAsync(this);
}
MobileAds.initialize(this, initializationStatus -> {
});
// Initiate the interstitial ad and onAdClosed listener
InterstitialAd.load(this, getString(R.string.interstitial_ad_unit_id), new AdRequest.Builder().build(),
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdDismissedFullScreenContent() {
requestNewInterstitial();
switch (mInterstitialAdActivity) {
case 0:
startActivity(new Intent(mContext, Locations.class));
break;
case 1:
startActivity(new Intent(mContext, PeopleInSpace.class));
break;
}
}
@Override
public void onAdShowedFullScreenContent() {
mInterstitialAd = null;
}
});
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
}
});
mAdView = findViewById(R.id.adView);
Bundle extras = new Bundle();
extras.putString("collapsible", "bottom");
mAdView.loadAd(new AdRequest.Builder().addNetworkExtrasBundle(AdMobAdapter.class, extras).build());
}
/**
* Reread the refresh rate and update views if needed such as prediction line, texts and their
* properties (Color, size, etc.).
*/
protected void onResume() {
super.onResume();
// Asks for a interstitial ad now so next time user starts a new activity we have it ready
requestNewInterstitial();
// Update decimal format
StringBuilder format = new StringBuilder("0");
for (int i = 0; i < mSharedPreferences.getInt("decimalType", 3); ++i) {
if (i == 0) format.append(".");
format.append("#");
}
mDecimalFormat = new DecimalFormat(format.toString());
// When activity was just paused
if (mStart) {
mRefreshRate = 1000 * (mSharedPreferences.getInt("refresh_Rate", 9) + 1);
if (mTimer != null) {
mTimer.cancel();
mTimer.purge();
mTimer = null;
}
mTimer = new Timer(); // Track ISS based on refresh rate
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
trackISS();
}
}, 0, mRefreshRate);
mMapType();
// When activity is killed or created for first time
} else {
mStart = true;
mTimer = new Timer();
}
// Update the color and size of polylines if they are different in settings than what they are right now
mCurrentColor = Color.YELLOW;
mCurrentWidth = 5;
try {
mCurrentColor = mSharedPreferences.getInt("colorType", Color.YELLOW);
mCurrentWidth = mSharedPreferences.getInt("sizeType", 5);
} catch (ClassCastException e) {
Toast.makeText(mContext, R.string.data_corrupted, Toast.LENGTH_LONG).show();
mSharedPreferences.edit().clear().apply();
}
if (mPolyLine != null) {
if (mMap != null) {
// Color needs updating?
if (mPolyLine.getColor() != mCurrentColor) {
for (int i = 0; mPolyArray[i] != null && i < mPolyArray.length - 1; ++i) {
mPolyArray[i].setColor(mCurrentColor);
}
}
// What about their size?
if (mPolyLine.getWidth() != mCurrentWidth) {
for (int i = 0; mPolyArray[i] != null && i < mPolyArray.length - 1; ++i) {
mPolyArray[i].setWidth(mCurrentWidth);
}
}
} else {
Toast.makeText(mContext, R.string.errorMap, Toast.LENGTH_SHORT).show();
}
}
// If user even wants the additional info, and their properties have been changed, update them
if (mDescription.getVisibility() == View.VISIBLE && !mSharedPreferences.getBoolean("info_ISS", true)) {
mDescription.setVisibility(View.GONE);
} else if (mDescription.getVisibility() == View.GONE && mSharedPreferences.getBoolean("info_ISS", true)) {
mDescription.setVisibility(View.VISIBLE);
}
// Update text color if different than settings
int textColor = mSharedPreferences.getInt("colorText", Color.YELLOW);
if (mLatLong.getCurrentTextColor() != textColor) {
mLatLong.setTextColor(textColor);
mDescription.setTextColor(textColor);
}
// Update text outline color if different
int textOutlineColor = mSharedPreferences.getInt("colorHighlightText", Color.BLACK);
if (mLatLong.getShadowColor() != mSharedPreferences.getInt("colorHighlightText", Color.BLACK)) {
mLatLong.setShadowLayer(6, 0, 0, textOutlineColor);
mDescription.setShadowLayer(6, 0, 0, textOutlineColor);
}
// Update text size as well if different
int textSize = mSharedPreferences.getInt("textSizeType", 12);
if (mLatLong.getTextSize() != textSize) {
mLatLong.setTextSize(textSize);
mDescription.setTextSize(textSize);
}
if (mAdView != null) {
mAdView.resume();
}
mSuccess = 0;
}
/**
* Cancel any request on Volley after user goes to another activity.
*/
protected void onPause() {
super.onPause();
if (mRequestQueue != null) {
mRequestQueue.cancelAll(TAG);
}
if (mTimer != null) {
mTimer.cancel();
mTimer.purge();
}
if (mAdView != null) {
mAdView.pause();
}
mTimer = null;
}
/**
* Destroy additional members when activity is gone.
*/
@Override
protected void onDestroy() {
super.onDestroy();
if (mAdView != null) {
mAdView.destroy();
}
if (mPolyTimer != null) {
mPolyTimer.cancel();
mPolyTimer.purge();
}
mPolyTimer = null;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
*/
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;
mMapType();
if (mTimer == null) {
mTimer = new Timer();
}
// Every 90 minutes, update the polylines automatically
if (mPolyTimer == null) {
mPolyTimer = new Timer();
TimerTask hourlyTask = new TimerTask() {
@Override
public void run() {
asyncTaskPolyline();
}
};
mPolyTimer.schedule(hourlyTask, 0L, 5400000); // 90 minutes
}
mMarkerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.iss_2011));
mMarkerOptions.anchor(0.5f, 0.5f);
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
trackISS();
}
}, 0, mRefreshRate);
}
/**
* Background call for updatePolyline
*/
private void asyncTaskPolyline() {
runOnUiThread(() -> {
mMap.clear();
trackISS();
mPoly = 0;
mPolyCounter = 0;
});
AsyncTask.execute(() -> {
try {
mThreadManager = true;
Date currentDate = new Date();
mProgress = 0;
for (int i = 0; i < 20; ++i) {
int mLastPatience = 0;
while (i > 0 && mLastPatience < 10 && mProgress < i) {
Thread.sleep(300);
++mLastPatience;
}
if (mLastPatience >= 10) {
runOnUiThread(() -> Toast.makeText(mContext, R.string.polyError, Toast.LENGTH_SHORT).show());
break;
}
updatePolyline(currentDate);
Thread.sleep(1500);
}
mThreadManager = false;
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* Changes the map type to match the one from settings. If it's the same just return.
*/
private void mMapType() {
int current = Integer.parseInt(mSharedPreferences.getString("mapType", "2"));
if (mMap != null) {
if (mMap.getMapType() == current) {
return;
}
mMap.setMapType(current);
}
}
/**
* Get the Lat and Lon of ISS and move the map to that position when called.
*/
private void trackISS() {
final String url = "https://api.wheretheiss.at/v1/satellites/25544";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
null, response -> {
try {
mSuccess = 0; // Server responded successfully
final double latParameter = Double.parseDouble(response.getString("latitude"));
final double lngParameter = Double.parseDouble(response.getString("longitude"));
final LatLng ISS = new LatLng(latParameter, lngParameter);
final String LAT;
final String LNG;
if (latParameter < 0) {
LAT = mDecimalFormat.format(latParameter) + "° S";
} else {
LAT = mDecimalFormat.format(latParameter) + "° N";
}
if (lngParameter < 0) {
LNG = mDecimalFormat.format(lngParameter) + "° W";
} else {
LNG = mDecimalFormat.format(lngParameter) + "° E";
}
final String position = LAT + ", " + LNG;
final String visibility = response.getString("visibility");
final StringBuilder moreInfo = new StringBuilder();
moreInfo.append("Altitude: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("altitude")))).append(" km").append("\n")
.append("Velocity: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("velocity")))).append(" kph").append("\n")
.append("Footprint: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("footprint")))).append(" km").append("\n")
.append("Solar LAT: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("solar_lat")))).append("°").append("\n")
.append("Solar LON: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("solar_lon")))).append("°").append("\n")
.append("Visibility: ").append(visibility.substring(0, 1).toUpperCase()).append(visibility.substring(1)).append("\n");
MapsActivity.this.runOnUiThread(() -> {
if (mOnce) {
mMap.moveCamera(CameraUpdateFactory.newLatLng(ISS));
if (mMap.getUiSettings().isScrollGesturesEnabled()) {
mMap.getUiSettings().setScrollGesturesEnabled(false);
}
mOnce = false;
} else if (mSharedPreferences.getBoolean("lock_ISS", false)) {
mMap.moveCamera(CameraUpdateFactory.newLatLng(ISS));
if (mMap.getUiSettings().isScrollGesturesEnabled()) {
mMap.getUiSettings().setScrollGesturesEnabled(false);
}
} else if (!mSharedPreferences.getBoolean("lock_ISS", false)) {
mMap.getUiSettings().setScrollGesturesEnabled(true);
}
if (mMarker != null) {
mMarker.remove();
}
mDescription.setText(moreInfo.toString());
mLatLong.setText(position);
mMarkerOptions.position(ISS);
mMarker = mMap.addMarker(mMarkerOptions);
});
} catch (Exception e) {
e.printStackTrace();
}
}, e -> {
// Server did not respond. Got 5 chances before stop trying.
if (++mSuccess <= 4) {
Toast.makeText(MapsActivity.this, getResources().getString(R.string.errorLessFive), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MapsActivity.this, R.string.errorFiveTimes, Toast.LENGTH_LONG).show();
if (mTimer != null) {
mTimer.cancel();
mTimer.purge();
}
mTimer = null;
}
});
jsonObjectRequest.setTag(TAG);
mRequestQueue.add(jsonObjectRequest);
}
/**
* Update polyline sets the future predictions of ISS's position for up to 90 minutes.
*/
private void updatePolyline(Date currentDate) {
long currentLong = currentDate.getTime() / 1000;
final long[] futureTen = new long[10];
for (int i = 0; i < futureTen.length; ++i) {
futureTen[i] = currentLong + (30L * mPoly++);
}
final StringBuilder urlBuilder = new StringBuilder();
for (long aFutureTen : futureTen) {
urlBuilder.append(aFutureTen).append(",");
}
urlBuilder.setLength(urlBuilder.length() - 1);
//TODO: As a user, I would like the option of changing the units from metric to imperial
final String units = "miles";
final String url = "https://api.wheretheiss.at/v1/satellites/25544/positions?timestamps=" +
urlBuilder +
"&units=" +
units;
final int finalStart = mPoly;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, response -> {
try {
final LatLng[] latLngs = new LatLng[10];
for (int i = 0; i < response.length(); ++i) {
latLngs[i] = new LatLng(response.getJSONObject(i).getDouble("latitude"),
response.getJSONObject(i).getDouble("longitude"));
}
MapsActivity.this.runOnUiThread(() -> {
if (finalStart == 10) {
for (int i = 0; i < futureTen.length - 1; ++i) {
mPolyLine = mMap.addPolyline(new PolylineOptions()
.add(latLngs[i], latLngs[i + 1])
.width(mCurrentWidth)
.color(mCurrentColor));
mPolyArray[mPolyCounter++] = mPolyLine;
}
} else {
mPolyArray[mPolyCounter++] = mMap.addPolyline(new PolylineOptions()
.add(mLast, latLngs[0])
.width(mCurrentWidth)
.color(mCurrentColor));
for (int i = 0; i < futureTen.length - 1; ++i) {
mPolyArray[mPolyCounter++] = mMap.addPolyline(new PolylineOptions()
.add(latLngs[i], latLngs[i + 1])
.width(mCurrentWidth)
.color(mCurrentColor));
}
}
mLast = latLngs[latLngs.length - 1];
++mProgress;
});
} catch (Exception e) {
if (mLast == null) {
// TODO: Report crash
}
e.printStackTrace();
}
}, e -> {
});
mRequestQueue.add(jsonArrayRequest);
}
/**
* Initiate the drawer library by giving each of them their properties such as color, texts, and
* onClickListeners
*/
private void initiateBoomMenu() {
mBoomMenu = findViewById(R.id.action_bar_right_bmb);
mBoomMenu.setButtonEnum(ButtonEnum.Ham);
mBoomMenu.setPiecePlaceEnum(PiecePlaceEnum.HAM_4);
mBoomMenu.setButtonPlaceEnum(ButtonPlaceEnum.HAM_4);
mBoomMenu.setDuration(850);
for (int i = 0; i < mBoomMenu.getPiecePlaceEnum().pieceNumber(); i++) {
HamButton.Builder builder;
switch (i) {
case 0:
builder = new HamButton.Builder()
.listener(index -> {
Intent intent;
if (isLocationPermissionGranted()) {
getLocationPermission();
} else {
if (mInterstitialAd != null) {
mInterstitialAd.show(MapsActivity.this);
mInterstitialAdActivity = 0;
} else {
intent = new Intent(mContext, Locations.class);
startActivity(intent);
}
}
})
.normalImageRes(R.drawable.iss)
.normalTextRes(R.string.flybys_title)
.subNormalTextRes(R.string.flybys_summary)
.normalColor(Color.parseColor("#807E57C2"))
.highlightedColor(Color.parseColor("#807E57C2"))
.unableColor(Color.parseColor("#807E57C2"))
.rotateImage(false);
break;
case 1:
builder = new HamButton.Builder()
.listener(index -> {
Intent intent;
if (mInterstitialAd != null) {
mInterstitialAd.show(MapsActivity.this);
mInterstitialAdActivity = 1;
} else {
intent = new Intent(mContext, PeopleInSpace.class);
startActivity(intent);
}
})
.normalImageRes(R.drawable.astronaut)
.normalTextRes(R.string.space_title)
.subNormalTextRes(R.string.space_summary)
.normalColor(Color.parseColor("#80EF5350"))
.highlightedColor(Color.parseColor("#80EF5350"))
.unableColor(Color.parseColor("#80EF5350"))
.rotateImage(false);
break;
case 2:
builder = new HamButton.Builder()
.listener(index -> {
Intent intent;
/* Update the check box representing the app's service. If for example the service
exited not by the app, it shouldn't be checked. */
boolean Alert = isMyServiceRunning(com.restart.spacestationtracker.services.Alert.class);
if (Alert != mSharedPreferences.getBoolean("notification_ISS", false)) {
Toast.makeText(MapsActivity.this, R.string.errorNotByMe, Toast.LENGTH_LONG).show();
mSharedPreferences.edit().putBoolean("notification_ISS", Alert).apply();
}
intent = new Intent(mContext, Preferences.class);
startActivity(intent);
})
.normalImageRes(R.drawable.ic_settings)
.normalTextRes(R.string.settings_title)
.subNormalTextRes(R.string.settings_summary)
.normalColor(Color.parseColor("#8066BB6A"))
.highlightedColor(Color.parseColor("#8066BB6A"))
.unableColor(Color.parseColor("#8066BB6A"))
.rotateImage(false);
break;
case 3:
builder = new HamButton.Builder()
.listener(index -> {
Intent intent;
intent = new Intent(mContext, AboutActivity.class);
startActivity(intent);
})
.normalImageRes(R.drawable.ic_help_outline)
.normalTextRes(R.string.help_title)
.subNormalTextRes(R.string.help_summary)
.normalColor(Color.parseColor("#8029B6F6"))
.highlightedColor(Color.parseColor("#8029B6F6"))
.unableColor(Color.parseColor("#8029B6F6"))
.rotateImage(false);
break;
default:
return;
}
mBoomMenu.addBuilder(builder);
}
}
/**
* Check to see if user has given us the permission to access their location.
*
* @return True or false
*/
private boolean isLocationPermissionGranted() {
return Build.VERSION.SDK_INT >= 23 && mContext.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED;
}
/**
* Get the permissions needed for the Locations.class
*/
private void getLocationPermission() {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
/**
* If permission was granted, send the user to the new activity.
*
* @param requestCode For managing requests, in this case it's just 1
* @param permissions Would be nice to get internet and location
* @param grantResults The ACCESS_FINE_LOCATION must be granted
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mInterstitialAd != null) {
mInterstitialAd.show(MapsActivity.this);
mInterstitialAdActivity = 0;
} else {
startActivity(new Intent(mContext, Locations.class));
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
/**
* Checks to see if a service is running on the phone and to update the check points
* on Settings based on its return.
*
* @param serviceClass Class service searching for
* @return Returns if user's phone is running the given service.
* @noinspection SameParameterValue notifications are disabled for now
*/
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
/**
* Starts a two step animation process. One gets executed after another.
*
* @param mTitleTextView A view to the top text widget
* @param activity MapsActivity.java
*/
private void startAnimation(final View mTitleTextView, final Activity activity) {
mSharedPreferences.edit().putBoolean(getString(R.string.firstTime), false).apply();
mFirstTime = false;
new SpotlightView.Builder(activity)
.introAnimationDuration(400)
.enableRevealAnimation(true)
.performClick(true)
.fadeinTextDuration(400)
.headingTvColor(Color.parseColor("#6441A5"))
.headingTvSize(32)
.headingTvText(getString(R.string.tutorial_one_title))
.subHeadingTvColor(Color.parseColor("#ffffff"))
.subHeadingTvSize(16)
.subHeadingTvText(getString(R.string.tutorialOne))
.maskColor(Color.parseColor("#dc000000"))
.target(mTitleTextView)
.lineAnimDuration(400)
.lineAndArcColor(Color.parseColor("#6441A5"))
.dismissOnTouch(true)
.usageId("1")
.setListener(s -> new SpotlightView.Builder(activity)
.introAnimationDuration(400)
.enableRevealAnimation(true)
.performClick(true)
.fadeinTextDuration(400)
.headingTvColor(Color.parseColor("#6441A5"))
.headingTvSize(32)
.headingTvText(getString(R.string.tutorial_two_title))
.subHeadingTvColor(Color.parseColor("#ffffff"))
.subHeadingTvSize(16)
.subHeadingTvText(getString(R.string.tutorialTwo))
.maskColor(Color.parseColor("#dc000000"))
.target(mBoomMenu)
.lineAnimDuration(400)
.lineAndArcColor(Color.parseColor("#6441A5"))
.dismissOnTouch(true)
.usageId("2")
.setListener(s1 -> initializeConsent()).show()).show();
}
/**
* Creates switch case for action bar icons
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.reset:
if (!mThreadManager) {
asyncTaskPolyline();
} else {
Toast.makeText(mContext, R.string.errorWaitPoly, Toast.LENGTH_SHORT).show();
}
return true;
case R.id.stream:
onISS();
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Creates the icons in the action bar
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
/**
* Start the LiveStream activity
*/
private void onISS() {
Intent intent = new Intent(mContext, LiveStream.class);
startActivity(intent);
}
/**
* Request for a new interstitial ad
*/
private void requestNewInterstitial() {
if (consentInformation == null || !consentInformation.canRequestAds()) {
return;
}
// Initiate the interstitial ad and onAdClosed listener
InterstitialAd.load(this, getString(R.string.interstitial_ad_unit_id), new AdRequest.Builder().build(),
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdDismissedFullScreenContent() {
switch (mInterstitialAdActivity) {
case 0:
startActivity(new Intent(mContext, Locations.class));
break;
case 1:
startActivity(new Intent(mContext, PeopleInSpace.class));
break;
}
}
@Override
public void onAdShowedFullScreenContent() {
mInterstitialAd = null;
}
});
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
}
});
}
@Override
public void onClick(View v) {
}
}