aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/cgeonavigate.java
blob: f5da2a19ebc627aa409e30ca2565c38f6e1e3023 (plain)
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
package cgeo.geocaching;

import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.HumanDistance;
import cgeo.geocaching.geopoint.IConversion;
import cgeo.geocaching.maps.CGeoMap;
import cgeo.geocaching.ui.CompassView;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.PeriodicHandler;

import org.apache.commons.lang3.StringUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class cgeonavigate extends AbstractActivity {

    private static final String EXTRAS_LONGITUDE = "longitude";
    private static final String EXTRAS_LATITUDE = "latitude";
    private static final String EXTRAS_NAME = "name";
    private static final String EXTRAS_GEOCODE = "geocode";
    private static final List<IWaypoint> coordinates = new ArrayList<IWaypoint>();
    private static final int MENU_MAP = 0;
    private static final int MENU_SWITCH_COMPASS_GPS = 1;
    private PowerManager pm = null;
    private cgGeo geo = null;
    private cgDirection dir = null;
    private UpdateLocationCallback geoUpdate = new update();
    private UpdateDirectionCallback dirUpdate = new UpdateDirection();
    private Geopoint dstCoords = null;
    private float cacheHeading = 0;
    private Float northHeading = null;
    private String title = null;
    private String name = null;
    private TextView navType = null;
    private TextView navAccuracy = null;
    private TextView navSatellites = null;
    private TextView navLocation = null;
    private TextView distanceView = null;
    private TextView headingView = null;
    private CompassView compassView = null;
    private PeriodicHandler updaterHandler = new PeriodicHandler(20) {

        @Override
        public void act() {
            if (compassView != null && northHeading != null) {
                compassView.updateNorth(northHeading, cacheHeading);
            }
        }

    };
    private String geocode;

    public cgeonavigate() {
        super("c:geo-compass", true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTheme();
        setContentView(R.layout.navigate);
        setTitle(res.getString(R.string.compass_title));

        // sensor & geolocation manager
        if (geo == null) {
            geo = app.startGeo(geoUpdate);
        }
        if (Settings.isUseCompass() && dir == null) {
            dir = app.startDir(this, dirUpdate);
        }

        // get parameters
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            geocode = extras.getString(EXTRAS_GEOCODE);
            title = geocode;
            name = extras.getString(EXTRAS_NAME);
            dstCoords = new Geopoint(extras.getDouble(EXTRAS_LATITUDE), extras.getDouble(EXTRAS_LONGITUDE));

            if (StringUtils.isNotBlank(name)) {
                if (StringUtils.isNotBlank(title)) {
                    title += ": " + name;
                } else {
                    title = name;
                }
            }
        } else {
            Intent pointIntent = new Intent(this, cgeopoint.class);
            startActivity(pointIntent);

            finish();
            return;
        }

        setGo4CacheAction();

        // set header
        setTitle();
        setDestCoords();

        if (geo != null) {
            geoUpdate.updateLocation(geo);
        }
        if (dir != null) {
            dirUpdate.updateDirection(dir);
        }

        // get textviews once
        compassView = (CompassView) findViewById(R.id.rose);
    }

    @Override
    public void onStart() {
        super.onStart();
        updaterHandler.start();
    }

    @Override
    public void onResume() {
        super.onResume();

        setGo4CacheAction();

        // sensor & geolocation manager
        if (geo == null) {
            geo = app.startGeo(geoUpdate);
        }
        if (Settings.isUseCompass() && dir == null) {
            dir = app.startDir(this, dirUpdate);
        }

        // keep backlight on
        if (pm == null) {
            pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        }
    }

    private void setGo4CacheAction() {
        if (StringUtils.isNotBlank(geocode)) {
            app.setAction(geocode);
        } else if (StringUtils.isNotBlank(name)) {
            app.setAction(name);
        }
    }

    @Override
    public void onStop() {
        if (geo != null) {
            geo = app.removeGeo();
        }
        if (dir != null) {
            dir = app.removeDir();
        }

        updaterHandler.stop();

        super.onStop();
    }

    @Override
    public void onPause() {
        if (geo != null) {
            geo = app.removeGeo();
        }
        if (dir != null) {
            dir = app.removeDir();
        }

        super.onPause();
    }

    @Override
    public void onDestroy() {
        if (geo != null) {
            geo = app.removeGeo();
        }
        if (dir != null) {
            dir = app.removeDir();
        }

        compassView.destroyDrawingCache();
        compassView = null;

        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (Settings.isUseCompass()) {
            menu.add(0, MENU_SWITCH_COMPASS_GPS, 0, res.getString(R.string.use_gps)).setIcon(android.R.drawable.ic_menu_compass);
        } else {
            menu.add(0, MENU_SWITCH_COMPASS_GPS, 0, res.getString(R.string.use_compass)).setIcon(android.R.drawable.ic_menu_compass);
        }
        menu.add(0, MENU_MAP, 0, res.getString(R.string.caches_on_map)).setIcon(android.R.drawable.ic_menu_mapmode);
        menu.add(0, 2, 0, res.getString(R.string.destination_set)).setIcon(android.R.drawable.ic_menu_edit);
        if (coordinates.size() > 1) {
            SubMenu subMenu = menu.addSubMenu(0, 3, 0, res.getString(R.string.destination_select)).setIcon(android.R.drawable.ic_menu_myplaces);

            int cnt = 4;
            for (IWaypoint coordinate : coordinates) {
                subMenu.add(0, cnt, 0, coordinate.getName() + " (" + coordinate.getCoordType() + ")");
                cnt++;
            }

            return true;
        } else {
            menu.add(0, 3, 0, res.getString(R.string.destination_select)).setIcon(android.R.drawable.ic_menu_myplaces).setEnabled(false);

            return true;
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        MenuItem item = menu.findItem(MENU_SWITCH_COMPASS_GPS);
        if (Settings.isUseCompass()) {
            item.setTitle(res.getString(R.string.use_gps));
        } else {
            item.setTitle(res.getString(R.string.use_compass));
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == MENU_MAP) {
            CGeoMap.startActivityCoords(this, dstCoords, null, null);
        } else if (id == MENU_SWITCH_COMPASS_GPS) {
            boolean oldSetting = Settings.isUseCompass();
            Settings.setUseCompass(!oldSetting);
            invalidateOptionsMenuCompatible();
            if (oldSetting) {
                if (dir != null) {
                    dir = app.removeDir();
                }
            } else {
                if (dir == null) {
                    dir = app.startDir(this, dirUpdate);
                }
            }
        } else if (id == 2) {
            Intent pointIntent = new Intent(this, cgeopoint.class);
            startActivity(pointIntent);

            finish();
            return true;
        } else if (id > 3 && coordinates.get(id - 4) != null) {
            final IWaypoint coordinate = coordinates.get(id - 4);

            title = coordinate.getName();
            dstCoords = coordinate.getCoords();
            setTitle();
            setDestCoords();
            updateDistanceInfo();

            Log.d(Settings.tag, "destination set: " + title + " (" + dstCoords + ")");
            return true;
        }

        return false;
    }

    private void setTitle() {
        if (StringUtils.isNotBlank(title)) {
            setTitle(title);
        } else {
            setTitle(res.getString(R.string.navigation));
        }
    }

    private void setDestCoords() {
        if (dstCoords == null) {
            return;
        }

        ((TextView) findViewById(R.id.destination)).setText(dstCoords.toString());
    }

    public void setDest(final Geopoint coords) {
        if (coords == null) {
            return;
        }

        title = "some place";
        setTitle();
        setDestCoords();

        dstCoords = coords;
        updateDistanceInfo();
    }

    public Geopoint getCoordinatesNow() {
        return geo.coordsNow;
    }

    private void updateDistanceInfo() {
        if (geo == null || geo.coordsNow == null || dstCoords == null) {
            return;
        }

        if (distanceView == null) {
            distanceView = (TextView) findViewById(R.id.distance);
        }
        if (headingView == null) {
            headingView = (TextView) findViewById(R.id.heading);
        }

        cacheHeading = geo.coordsNow.bearingTo(dstCoords);
        distanceView.setText(HumanDistance.getHumanDistance(geo.coordsNow.distanceTo(dstCoords)));
        headingView.setText(Math.round(cacheHeading) + "°");
    }

    private class update implements UpdateLocationCallback {

        @Override
        public void updateLocation(cgGeo geo) {
            if (geo == null) {
                return;
            }

            try {
                if (navType == null || navLocation == null || navAccuracy == null) {
                    navType = (TextView) findViewById(R.id.nav_type);
                    navAccuracy = (TextView) findViewById(R.id.nav_accuracy);
                    navSatellites = (TextView) findViewById(R.id.nav_satellites);
                    navLocation = (TextView) findViewById(R.id.nav_location);
                }

                if (geo.coordsNow != null) {
                    String satellites = null;
                    if (geo.satellitesFixed > 0) {
                        satellites = res.getString(R.string.loc_sat) + ": " + geo.satellitesFixed + "/" + geo.satellitesVisible;
                    } else if (geo.satellitesVisible >= 0) {
                        satellites = res.getString(R.string.loc_sat) + ": 0/" + geo.satellitesVisible;
                    } else {
                        satellites = "";
                    }
                    navSatellites.setText(satellites);
                    navType.setText(res.getString(geo.locationProvider.resourceId));

                    if (geo.accuracyNow >= 0) {
                        if (Settings.isUseMetricUnits()) {
                            navAccuracy.setText("±" + Math.round(geo.accuracyNow) + " m");
                        } else {
                            navAccuracy.setText("±" + Math.round(geo.accuracyNow * IConversion.METERS_TO_FEET) + " ft");
                        }
                    } else {
                        navAccuracy.setText(null);
                    }

                    if (geo.altitudeNow != null) {
                        final String humanAlt = HumanDistance.getHumanDistance(geo.altitudeNow.floatValue() / 1000);
                        navLocation.setText(geo.coordsNow + " | " + humanAlt);
                    } else {
                        navLocation.setText(geo.coordsNow.toString());
                    }

                    updateDistanceInfo();
                } else {
                    navType.setText(null);
                    navAccuracy.setText(null);
                    navLocation.setText(res.getString(R.string.loc_trying));
                }

                if (!Settings.isUseCompass() || geo.speedNow > 5) { // use GPS when speed is higher than 18 km/h
                    northHeading = geo.bearingNow;
                }
            } catch (Exception e) {
                Log.w(Settings.tag, "Failed to update location.");
            }
        }
    }

    private class UpdateDirection implements UpdateDirectionCallback {

        @Override
        public void updateDirection(cgDirection dir) {
            if (dir == null || dir.directionNow == null) {
                return;
            }

            if (geo == null || geo.speedNow <= 5) { // use compass when speed is lower than 18 km/h
                northHeading = dir.directionNow;
            }
        }
    }

    public static void startActivity(final Context context, final String geocode, final String displayedName, final Geopoint coords, final Collection<IWaypoint> coordinatesWithType) {
        coordinates.clear();
        if (coordinatesWithType != null) { // avoid possible NPE
            coordinates.addAll(coordinatesWithType);
        }

        final Intent navigateIntent = new Intent(context, cgeonavigate.class);
        navigateIntent.putExtra(EXTRAS_LATITUDE, coords.getLatitude());
        navigateIntent.putExtra(EXTRAS_LONGITUDE, coords.getLongitude());
        navigateIntent.putExtra(EXTRAS_GEOCODE, geocode.toUpperCase());
        if (null != displayedName) {
            navigateIntent.putExtra(EXTRAS_NAME, displayedName);
        }
        context.startActivity(navigateIntent);
    }
}