-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
TabActivity.java
500 lines (417 loc) · 17.5 KB
/
TabActivity.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
package org.inventivetalent.trashapp;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.hardware.GeomagneticField;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProviders;
import androidx.preference.PreferenceManager;
import androidx.room.Room;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.inventivetalent.trashapp.common.Constants;
import org.inventivetalent.trashapp.common.DbTrashcanQueryTask;
import org.inventivetalent.trashapp.common.LatLon;
import org.inventivetalent.trashapp.common.OverpassBoundingBox;
import org.inventivetalent.trashapp.common.RotationBuffer;
import org.inventivetalent.trashapp.common.TrashCanFinderTask;
import org.inventivetalent.trashapp.common.TrashCanResultHandler;
import org.inventivetalent.trashapp.common.TrashcanQuery;
import org.inventivetalent.trashapp.common.TrashcanUpdater;
import org.inventivetalent.trashapp.common.Util;
import org.inventivetalent.trashapp.common.db.AppDatabase;
import org.inventivetalent.trashapp.common.db.Migrations;
import org.inventivetalent.trashapp.ui.main.PageViewModel;
import org.inventivetalent.trashapp.ui.main.SectionsPagerAdapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.inventivetalent.trashapp.common.Constants.DEFAULT_SEARCH_RADIUS;
import static org.inventivetalent.trashapp.common.Constants.MAX_SEARCH_RADIUS;
import static org.inventivetalent.trashapp.common.Constants.ONE_METER_DEG;
import static org.inventivetalent.trashapp.common.Constants.REQUEST_LOCATION_PERMS_CODE;
import static org.inventivetalent.trashapp.common.Constants.SEARCH_STEP;
import static org.inventivetalent.trashapp.common.OverpassResponse.elementsSortedByDistanceFrom;
public class TabActivity extends AppCompatActivity implements TrashCanResultHandler, TrashcanUpdater {
protected static TabActivity instance;
private FirebaseAnalytics mFirebaseAnalytics;
private SharedPreferences sharedPreferences;
private boolean debug;
private LocationManager mLocationManager;
public static Location lastKnownLocation;
public static Location searchCenter;
public static GeomagneticField geoField;
private SensorManager mSensorManager;
private float[] mGravity = new float[3];
private boolean gravitySet;
private float[] mGeomagnetic = new float[3];
private boolean magneticSet;
public static float[] lastKnownRotation = new float[3];
public long lastUpdateStart = 0;
public long lastLiveUpdateTime = 0;
public static RotationBuffer rotationBuffer = new RotationBuffer();
boolean initialSearchCompleted = false;
public static List<LatLon> nearbyTrashCans = new ArrayList<>();
public static LatLon closestTrashCan;
private int searchItaration = 0;
protected AppDatabase appDatabase;
private CustomViewPager viewPager;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest = new LocationRequest()
.setInterval(Constants.LOCATION_INTERVAL)
.setFastestInterval(Constants.LOCATION_INTERVAL_MIN)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
Log.i("TrashApp", "onLocationChanged");
Log.i("TrashApp", location.toString());
setLastKnownLocation(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
private final LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
Log.i("TrashApp", "onLocationResult");
Log.i("TrashApp", locationResult.toString());
setLastKnownLocation(locationResult.getLastLocation());
}
};
private final SensorEventListener mSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
System.arraycopy(event.values, 0, mGravity, 0, event.values.length);
gravitySet = true;
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
System.arraycopy(event.values, 0, mGeomagnetic, 0, event.values.length);
magneticSet = true;
}
if (gravitySet && magneticSet) {
float[] r = new float[9];
float[] i = new float[9];
if (SensorManager.getRotationMatrix(r, i, mGravity, mGeomagnetic)) {
SensorManager.getOrientation(r, lastKnownRotation);
rotationBuffer.add(lastKnownRotation[0]);
ViewModelProviders.of(TabActivity.this).get(PageViewModel.class).mRotation.setValue(lastKnownRotation[0]);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
public TabActivity() {
instance = this;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
// for (Map.Entry<String, ?> entry : sharedPreferences.getAll().entrySet()) {
// System.out.println(entry.getKey() + ": " + entry.getValue() + " (" + entry.getValue().getClass() + ")");
// }
debug = Util.getBoolean(sharedPreferences, "enable_debug", false);
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
if (packageInfo != null) {
Util.APP_VERSION_ID = packageInfo.versionCode;
Util.APP_VERSION_NAME = packageInfo.versionName;
}
} catch (Throwable throwable) {
Log.w("TabActivity", "Failed to init app version in Util", throwable);
}
Util.applyTheme(this, sharedPreferences);
setContentView(R.layout.activity_tab);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
Intent intent = getIntent();
if (intent != null) {
Log.i("TrashApp", intent.toString());
Log.i("TrashApp", intent.getAction());
Uri data = intent.getData();
Log.i("TrashApp", data != null ? data.toString() : "n/a");
}
MobileAds.initialize(this);
appDatabase = Room
.databaseBuilder(getApplicationContext(), AppDatabase.class, "trashapp")
.addMigrations(Migrations.MIGRATION_1_2)
.fallbackToDestructiveMigration()
.build();
// FloatingActionButton fab = findViewById(R.id.fab);
//
// fab.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
Util.showDebugDBAddressLogToast(this);
// ATTENTION: This was auto-generated to handle app links.
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
if (Intent.ACTION_VIEW.equals(appLinkAction) && appLinkData != null) {
String tabPath = appLinkData.getLastPathSegment();
if (tabPath != null) {
switch (tabPath) {
case "map":
viewPager.setCurrentItem(1);
break;
case "compass":
default:
viewPager.setCurrentItem(0);
break;
}
}
}
// Monitor launch times and interval from installation
// RateThisApp.onCreate(this);
// If the condition is satisfied, "Rate this app" dialog will be shown
// RateThisApp.showRateDialogIfNeeded(this);
}
@Override
protected void onResume() {
super.onResume();
Log.i("TabActivity", "onResume");
instance = this;
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if (mSensorManager == null) {
Toast.makeText(this, "Your device doesn't support sensors", Toast.LENGTH_LONG).show();
exitApp();
return;
}
Sensor magneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
Sensor accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(mSensorListener, magneticSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(mSensorListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (requestLocationUpdates(true)) {
lookForTrashCans();
}
}
@Override
protected void onPause() {
super.onPause();
if (mSensorManager != null) { mSensorManager.unregisterListener(mSensorListener); }
// if (mLocationManager != null) { mLocationManager.removeUpdates(mLocationListener); }
if (fusedLocationProviderClient != null) { fusedLocationProviderClient.removeLocationUpdates(locationCallback); }
}
@Override
protected void onDestroy() {
instance = null;
super.onDestroy();
}
void setLastKnownLocation(Location location) {
if (location != null) {
geoField = new GeomagneticField(
(float) location.getLatitude(),
(float) location.getLongitude(),
(float) location.getAltitude(),
System.currentTimeMillis()
);
lastKnownLocation = location;
if (searchCenter == null || !sharedPreferences.getBoolean("moving_search", false) || searchCenter.distanceTo(lastKnownLocation) > 1) {
searchCenter = lastKnownLocation;
}
ViewModelProviders.of(this).get(PageViewModel.class).mLocation.setValue(location);
if (!initialSearchCompleted) {
lookForTrashCans();
}
updateClosestTrashcan(nearbyTrashCans);
}
}
boolean requestLocationUpdates(boolean ask) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.i("TrashApp", "Location permissions not granted");
if (ask) {
Log.i("TrashApp", "Requesting location permissions");
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION }, REQUEST_LOCATION_PERMS_CODE);
return false;
}
Log.i("TrashApp", "Location permissions not granted and can't ask - exiting!");
Toast.makeText(this, "This app requires location permissions", Toast.LENGTH_LONG).show();
exitApp();
return false;
}
Log.i("TrashApp", "Location permissions granted!");
// has permission, request!
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null/*Looper*/);
// //TODO: use google play services for location updates
// mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
// LOCATION_REFRESH_DISTANCE, mLocationListener);
// mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_REFRESH_TIME,
// LOCATION_REFRESH_DISTANCE, mLocationListener);
Log.i("TrashApp", "Trying to get last known location from providers");
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else {
Log.i("TrashApp", "got last known location from gps provider");
}
if (location == null) {
location = mLocationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
} else {
Log.i("TrashApp", "got last known location from network provider");
}
setLastKnownLocation(location);
Log.i("TrashApp", lastKnownLocation != null ? lastKnownLocation.toString() : "n/a");
mLocationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, mLocationListener, null);
return true;
}
@Override
public void lookForTrashCans() {
if (searchCenter == null) {
if (lastKnownLocation != null) {
searchCenter = lastKnownLocation;
} else {
return;
}
}
if (lastUpdateStart != 0 && System.currentTimeMillis() - lastUpdateStart < 5000) {
return;
}
lastUpdateStart = System.currentTimeMillis();
Log.i("TrashApp", "Looking for trash cans");
Toast.makeText(this, R.string.searching, Toast.LENGTH_SHORT).show();
double searchRadius = Util.getInt(sharedPreferences, "search_radius_start", DEFAULT_SEARCH_RADIUS) + SEARCH_STEP * searchItaration;// meters
double searchRadiusDeg = searchRadius * ONE_METER_DEG;
Log.i("TrashApp", "Radius: " + (searchRadius / 1000) + "km / " + searchRadius + "m / " + searchRadiusDeg + "deg");
double lat = searchCenter.getLatitude();
double lon = searchCenter.getLongitude();
OverpassBoundingBox boundingBox = new OverpassBoundingBox(lat - searchRadiusDeg, lon - searchRadiusDeg, lat + searchRadiusDeg, lon + searchRadiusDeg);
List<String> types = Util.createFilterFromPreferences(sharedPreferences);
if (types.isEmpty()) {
Toast.makeText(this, R.string.warn_empty_filter, Toast.LENGTH_SHORT).show();
}
Log.i("TrashApp", boundingBox.toCoordString());
TrashcanQuery query = new TrashcanQuery(boundingBox, types);
//TODO: make this more efficient, i.e. don't run both
new DbTrashcanQueryTask(this).execute(query);
if (System.currentTimeMillis() - lastLiveUpdateTime > 10000) {
new TrashCanFinderTask(this, this).execute(query);
lastLiveUpdateTime = System.currentTimeMillis();
}
}
@Override
public AppDatabase getDatabase() {
return appDatabase;
}
@Override
public void handleTrashCanLocations(List<? extends LatLon> elements, boolean isCached) {
Log.i("TrashApp", "Got trashcan locations (cached: " + isCached + ")");
if (debug) {
Toast.makeText(this, "Got " + elements.size() + " locations, c: " + isCached, Toast.LENGTH_SHORT).show();
}
initialSearchCompleted = true;
// elements = convertElementsToPoints(elements);
Log.i("TrashApp", elements.toString());
if (elements.isEmpty()) {
if (!isCached && Util.getInt(sharedPreferences, "search_radius_start", DEFAULT_SEARCH_RADIUS) + SEARCH_STEP * searchItaration < Util.getInt(sharedPreferences, "search_radius_max", MAX_SEARCH_RADIUS)) {
// still below max radius, keep looking
searchItaration++;
lookForTrashCans();
} else {
// reset
searchItaration = 0;
if (!isCached) {
Toast.makeText(this, R.string.err_no_trashcans, Toast.LENGTH_LONG).show();
}
}
} else if (!isCached) {
Util.insertTrashcanResult(appDatabase, elements);
List<String> filter = Util.createFilterFromPreferences(sharedPreferences);
Log.i("TabActivity", filter.toString());
elements = Util.filterResponse(elements, filter);
}
updateClosestTrashcan(elements);
}
public void updateClosestTrashcan(Collection<? extends LatLon> elements) {
// Set<LatLon> joined = new HashSet<>();
// joined.addAll(elements);
// joined.addAll(nearbyTrashCans);
// elements = joined;
if (elements.isEmpty()) {
closestTrashCan = null;
ViewModelProviders.of(this).get(PageViewModel.class).mClosestCan.setValue(null);
} else {
List<? extends LatLon> sortedElements = elementsSortedByDistanceFrom(elements, lastKnownLocation);
// no need to convert to points again
nearbyTrashCans.clear();
nearbyTrashCans.addAll(sortedElements);
// int i = 0;
// for (OverpassResponse.Element element : elements) {
// Log.i("TrashApp", (i++) + " " + element.toLocation() + " => " + lastKnownLocation.distanceTo(element.toLocation()));
// }
LatLon closest = sortedElements.get(0);
ViewModelProviders.of(this).get(PageViewModel.class).mClosestCan.setValue(closest);
closestTrashCan = closest;
// reset
searchItaration = 0;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_LOCATION_PERMS_CODE) {
// just try to init the updates again
if (requestLocationUpdates(false)) {
lookForTrashCans();
}
}
}
void exitApp() {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
}