Merge branch 'master' of ssh://git.gag.com/scm/git/fw/altos
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / AltosDroid.java
1 /*
2  * Copyright © 2012-2013 Mike Beattie <mike@ethernal.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package org.altusmetrum.AltosDroid;
19
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.Timer;
23 import java.util.TimerTask;
24
25 import android.app.Activity;
26 import android.bluetooth.BluetoothAdapter;
27 import android.bluetooth.BluetoothDevice;
28 import android.content.Intent;
29 import android.content.Context;
30 import android.content.ComponentName;
31 import android.content.ServiceConnection;
32 import android.content.DialogInterface;
33 import android.os.IBinder;
34 import android.os.Bundle;
35 import android.os.Handler;
36 import android.os.Message;
37 import android.os.Messenger;
38 import android.os.RemoteException;
39 import android.support.v4.app.FragmentActivity;
40 import android.support.v4.app.FragmentManager;
41 import android.util.DisplayMetrics;
42 import android.util.Log;
43 import android.view.Menu;
44 import android.view.MenuInflater;
45 import android.view.MenuItem;
46 import android.view.Window;
47 import android.view.View;
48 import android.widget.TabHost;
49 import android.widget.TextView;
50 import android.widget.RelativeLayout;
51 import android.widget.Toast;
52 import android.app.AlertDialog;
53 import android.location.Location;
54
55 import org.altusmetrum.altoslib_5.*;
56
57 public class AltosDroid extends FragmentActivity implements AltosUnitsListener {
58         // Debugging
59         static final String TAG = "AltosDroid";
60         static final boolean D = true;
61
62         // Message types received by our Handler
63
64         public static final int MSG_STATE           = 1;
65         public static final int MSG_UPDATE_AGE      = 2;
66
67         // Intent request codes
68         public static final int REQUEST_CONNECT_DEVICE = 1;
69         public static final int REQUEST_ENABLE_BT      = 2;
70
71         public static FragmentManager   fm;
72
73         private BluetoothAdapter mBluetoothAdapter = null;
74
75         // Layout Views
76         private TextView mTitle;
77
78         // Flight state values
79         private TextView mCallsignView;
80         private TextView mRSSIView;
81         private TextView mSerialView;
82         private TextView mFlightView;
83         private RelativeLayout mStateLayout;
84         private TextView mStateView;
85         private TextView mAgeView;
86
87         // field to display the version at the bottom of the screen
88         private TextView mVersion;
89
90         private double frequency;
91         private int telemetry_rate;
92
93         // Tabs
94         TabHost         mTabHost;
95         AltosViewPager  mViewPager;
96         TabsAdapter     mTabsAdapter;
97         ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
98         int             tabHeight;
99
100         // Timer and Saved flight state for Age calculation
101         private Timer timer;
102         AltosState saved_state;
103
104         // Service
105         private boolean mIsBound   = false;
106         private Messenger mService = null;
107         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
108
109         // Text to Speech
110         private AltosVoice mAltosVoice = null;
111
112         // The Handler that gets information back from the Telemetry Service
113         static class IncomingHandler extends Handler {
114                 private final WeakReference<AltosDroid> mAltosDroid;
115                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
116
117                 @Override
118                 public void handleMessage(Message msg) {
119                         AltosDroid ad = mAltosDroid.get();
120
121                         switch (msg.what) {
122                         case MSG_STATE:
123                                 if(D) Log.d(TAG, "MSG_STATE");
124                                 TelemetryState telemetry_state = (TelemetryState) msg.obj;
125                                 if (telemetry_state == null) {
126                                         Log.d(TAG, "telemetry_state null!");
127                                         return;
128                                 }
129
130                                 ad.update_state(telemetry_state);
131                                 break;
132                         case MSG_UPDATE_AGE:
133                                 if(D) Log.d(TAG, "MSG_UPDATE_AGE");
134                                 ad.update_age();
135                                 break;
136                         }
137                 }
138         };
139
140
141         private ServiceConnection mConnection = new ServiceConnection() {
142                 public void onServiceConnected(ComponentName className, IBinder service) {
143                         mService = new Messenger(service);
144                         try {
145                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
146                                 msg.replyTo = mMessenger;
147                                 mService.send(msg);
148                         } catch (RemoteException e) {
149                                 // In this case the service has crashed before we could even do anything with it
150                         }
151                 }
152
153                 public void onServiceDisconnected(ComponentName className) {
154                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
155                         mService = null;
156                 }
157         };
158
159         void doBindService() {
160                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
161                 mIsBound = true;
162         }
163
164         void doUnbindService() {
165                 if (mIsBound) {
166                         // If we have received the service, and hence registered with it, then now is the time to unregister.
167                         if (mService != null) {
168                                 try {
169                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
170                                         msg.replyTo = mMessenger;
171                                         mService.send(msg);
172                                 } catch (RemoteException e) {
173                                         // There is nothing special we need to do if the service has crashed.
174                                 }
175                         }
176                         // Detach our existing connection.
177                         unbindService(mConnection);
178                         mIsBound = false;
179                 }
180         }
181
182         public void registerTab(AltosDroidTab mTab) {
183                 mTabs.add(mTab);
184         }
185
186         public void unregisterTab(AltosDroidTab mTab) {
187                 mTabs.remove(mTab);
188         }
189
190         public void units_changed(boolean imperial_units) {
191                 for (AltosDroidTab mTab : mTabs)
192                         mTab.units_changed(imperial_units);
193         }
194
195         void update_title(TelemetryState telemetry_state) {
196                 switch (telemetry_state.connect) {
197                 case TelemetryState.CONNECT_CONNECTED:
198                         if (telemetry_state.config != null) {
199                                 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
200                                                            telemetry_state.frequency);
201                                 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
202                                         str = str.concat(String.format(" %d bps",
203                                                                        AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
204                                 mTitle.setText(str);
205                         } else {
206                                 mTitle.setText(R.string.title_connected_to);
207                         }
208                         break;
209                 case TelemetryState.CONNECT_CONNECTING:
210                         mTitle.setText(R.string.title_connecting);
211                         break;
212                 case TelemetryState.CONNECT_READY:
213                 case TelemetryState.CONNECT_NONE:
214                         mTitle.setText(R.string.title_not_connected);
215                         break;
216                 }
217         }
218
219         void start_timer() {
220                 if (timer == null) {
221                         timer = new Timer();
222                         timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
223                 }
224         }
225
226         void stop_timer() {
227                 if (timer != null) {
228                         timer.cancel();
229                         timer.purge();
230                         timer = null;
231                 }
232         }
233
234         boolean registered_units_listener;
235
236         void update_state(TelemetryState telemetry_state) {
237
238                 if (!registered_units_listener) {
239                         registered_units_listener = true;
240                         AltosPreferences.register_units_listener(this);
241                 }
242
243                 update_title(telemetry_state);
244                 update_ui(telemetry_state.state, telemetry_state.location);
245                 if (telemetry_state.connect == TelemetryState.CONNECT_CONNECTED)
246                         start_timer();
247                 else
248                         stop_timer();
249         }
250
251         boolean same_string(String a, String b) {
252                 if (a == null) {
253                         if (b == null)
254                                 return true;
255                         return false;
256                 } else {
257                         if (b == null)
258                                 return false;
259                         return a.equals(b);
260                 }
261         }
262
263         void update_age() {
264                 if (saved_state != null)
265                         mAgeView.setText(String.format("%d", (System.currentTimeMillis() - saved_state.received_time + 500) / 1000));
266         }
267
268         void update_ui(AltosState state, Location location) {
269
270                 Log.d(TAG, "update_ui");
271
272                 int prev_state = AltosLib.ao_flight_invalid;
273
274                 AltosGreatCircle from_receiver = null;
275
276                 if (saved_state != null)
277                         prev_state = saved_state.state;
278
279                 if (state != null) {
280                         Log.d(TAG, String.format("prev state %d new state  %d\n", prev_state, state.state));
281                         if (state.state == AltosLib.ao_flight_stateless) {
282                                 boolean prev_locked = false;
283                                 boolean locked = false;
284
285                                 if(state.gps != null)
286                                         locked = state.gps.locked;
287                                 if (saved_state != null && saved_state.gps != null)
288                                         prev_locked = saved_state.gps.locked;
289                                 if (prev_locked != locked) {
290                                         String currentTab = mTabHost.getCurrentTabTag();
291                                         if (locked) {
292                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
293                                         } else {
294                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
295                                         }
296                                 }
297                         } else {
298                                 if (prev_state != state.state) {
299                                         String currentTab = mTabHost.getCurrentTabTag();
300                                         Log.d(TAG, "switch state");
301                                         switch (state.state) {
302                                         case AltosLib.ao_flight_boost:
303                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
304                                                 break;
305                                         case AltosLib.ao_flight_drogue:
306                                                 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
307                                                 break;
308                                         case AltosLib.ao_flight_landed:
309                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
310                                                 break;
311                                         case AltosLib.ao_flight_stateless:
312                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
313                                                 break;
314                                         }
315                                 }
316                         }
317
318                         if (location != null && state.gps != null && state.gps.locked) {
319                                 double altitude = 0;
320                                 if (location.hasAltitude())
321                                         altitude = location.getAltitude();
322                                 from_receiver = new AltosGreatCircle(location.getLatitude(),
323                                                                      location.getLongitude(),
324                                                                      altitude,
325                                                                      state.gps.lat,
326                                                                      state.gps.lon,
327                                                                      state.gps.alt);
328                         }
329
330                         if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
331                                 Log.d(TAG, "update callsign");
332                                 mCallsignView.setText(state.callsign);
333                         }
334                         if (saved_state == null || state.serial != saved_state.serial) {
335                                 Log.d(TAG, "update serial");
336                                 mSerialView.setText(String.format("%d", state.serial));
337                         }
338                         if (saved_state == null || state.flight != saved_state.flight) {
339                                 Log.d(TAG, "update flight");
340                                 if (state.flight == AltosLib.MISSING)
341                                         mFlightView.setText("");
342                                 else
343                                         mFlightView.setText(String.format("%d", state.flight));
344                         }
345                         if (saved_state == null || state.state != saved_state.state) {
346                                 Log.d(TAG, "update state");
347                                 if (state.state == AltosLib.ao_flight_stateless) {
348                                         mStateLayout.setVisibility(View.GONE);
349                                 } else {
350                                         mStateView.setText(state.state_name());
351                                         mStateLayout.setVisibility(View.VISIBLE);
352                                 }
353                         }
354                         if (saved_state == null || state.rssi != saved_state.rssi) {
355                                 Log.d(TAG, "update rssi");
356                                 mRSSIView.setText(String.format("%d", state.rssi));
357                         }
358                 }
359
360                 for (AltosDroidTab mTab : mTabs)
361                         mTab.update_ui(state, from_receiver, location, mTab == mTabsAdapter.currentItem());
362
363                 if (state != null)
364                         mAltosVoice.tell(state, from_receiver);
365
366                 saved_state = state;
367         }
368
369         private void onTimerTick() {
370                 try {
371                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
372                 } catch (RemoteException e) {
373                 }
374         }
375
376         static String pos(double p, String pos, String neg) {
377                 String  h = pos;
378                 if (p == AltosLib.MISSING)
379                         return "";
380                 if (p < 0) {
381                         h = neg;
382                         p = -p;
383                 }
384                 int deg = (int) Math.floor(p);
385                 double min = (p - Math.floor(p)) * 60.0;
386                 return String.format("%d°%9.4f\" %s", deg, min, h);
387         }
388
389         static String number(String format, double value) {
390                 if (value == AltosLib.MISSING)
391                         return "";
392                 return String.format(format, value);
393         }
394
395         static String integer(String format, int value) {
396                 if (value == AltosLib.MISSING)
397                         return "";
398                 return String.format(format, value);
399         }
400
401         @Override
402         public void onCreate(Bundle savedInstanceState) {
403                 super.onCreate(savedInstanceState);
404                 if(D) Log.e(TAG, "+++ ON CREATE +++");
405
406                 // Get local Bluetooth adapter
407                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
408
409                 // If the adapter is null, then Bluetooth is not supported
410                 if (mBluetoothAdapter == null) {
411                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
412                         finish();
413                 }
414
415                 fm = getSupportFragmentManager();
416
417                 // Set up the window layout
418                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
419                 setContentView(R.layout.altosdroid);
420                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
421
422                 // Create the Tabs and ViewPager
423                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
424                 mTabHost.setup();
425
426                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
427                 mViewPager.setOffscreenPageLimit(4);
428
429                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
430
431                 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
432                 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
433                 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
434                 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
435                 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
436
437
438                 // Scale the size of the Tab bar for different screen densities
439                 // This probably won't be needed when we start supporting ICS+ tabs.
440                 DisplayMetrics metrics = new DisplayMetrics();
441                 getWindowManager().getDefaultDisplay().getMetrics(metrics);
442                 int density = metrics.densityDpi;
443
444                 if (density==DisplayMetrics.DENSITY_XHIGH)
445                         tabHeight = 65;
446                 else if (density==DisplayMetrics.DENSITY_HIGH)
447                         tabHeight = 45;
448                 else if (density==DisplayMetrics.DENSITY_MEDIUM)
449                         tabHeight = 35;
450                 else if (density==DisplayMetrics.DENSITY_LOW)
451                         tabHeight = 25;
452                 else
453                         tabHeight = 65;
454
455                 for (int i = 0; i < 5; i++)
456                         mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;
457
458                 // Set up the custom title
459                 mTitle = (TextView) findViewById(R.id.title_left_text);
460                 mTitle.setText(R.string.app_name);
461                 mTitle = (TextView) findViewById(R.id.title_right_text);
462
463                 // Display the Version
464                 mVersion = (TextView) findViewById(R.id.version);
465                 mVersion.setText("Version: " + BuildInfo.version +
466                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
467                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
468
469                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
470                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
471                 mSerialView    = (TextView) findViewById(R.id.serial_value);
472                 mFlightView    = (TextView) findViewById(R.id.flight_value);
473                 mStateLayout   = (RelativeLayout) findViewById(R.id.state_container);
474                 mStateView     = (TextView) findViewById(R.id.state_value);
475                 mAgeView       = (TextView) findViewById(R.id.age_value);
476
477                 mAltosVoice = new AltosVoice(this);
478         }
479
480         @Override
481         public void onStart() {
482                 super.onStart();
483                 if(D) Log.e(TAG, "++ ON START ++");
484
485                 // Start Telemetry Service
486                 startService(new Intent(AltosDroid.this, TelemetryService.class));
487
488                 if (!mBluetoothAdapter.isEnabled()) {
489                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
490                         startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
491                 }
492
493                 doBindService();
494
495         }
496
497         @Override
498         public synchronized void onResume() {
499                 super.onResume();
500                 if(D) Log.e(TAG, "+ ON RESUME +");
501         }
502
503         @Override
504         public synchronized void onPause() {
505                 super.onPause();
506                 if(D) Log.e(TAG, "- ON PAUSE -");
507         }
508
509         @Override
510         public void onStop() {
511                 super.onStop();
512                 if(D) Log.e(TAG, "-- ON STOP --");
513
514                 doUnbindService();
515         }
516
517         @Override
518         public void onDestroy() {
519                 super.onDestroy();
520                 if(D) Log.e(TAG, "--- ON DESTROY ---");
521
522                 if (mAltosVoice != null) mAltosVoice.stop();
523                 stop_timer();
524         }
525
526         public void onActivityResult(int requestCode, int resultCode, Intent data) {
527                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
528                 switch (requestCode) {
529                 case REQUEST_CONNECT_DEVICE:
530                         // When DeviceListActivity returns with a device to connect to
531                         if (resultCode == Activity.RESULT_OK) {
532                                 connectDevice(data);
533                         }
534                         break;
535                 case REQUEST_ENABLE_BT:
536                         // When the request to enable Bluetooth returns
537                         if (resultCode == Activity.RESULT_OK) {
538                                 // Bluetooth is now enabled, so set up a chat session
539                                 //setupChat();
540                         } else {
541                                 // User did not enable Bluetooth or an error occured
542                                 Log.e(TAG, "BT not enabled");
543                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
544                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
545                                 finish();
546                         }
547                         break;
548                 }
549         }
550
551         private void connectDevice(String address) {
552                 // Attempt to connect to the device
553                 try {
554                         if (D) Log.d(TAG, "Connecting to " + address);
555                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, address));
556                 } catch (RemoteException e) {
557                 }
558         }
559
560         private void connectDevice(Intent data) {
561                 // Get the device MAC address
562                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
563                 connectDevice(address);
564         }
565
566         @Override
567         public boolean onCreateOptionsMenu(Menu menu) {
568                 MenuInflater inflater = getMenuInflater();
569                 inflater.inflate(R.menu.option_menu, menu);
570                 return true;
571         }
572
573         void setFrequency(double freq) {
574                 try {
575                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
576                 } catch (RemoteException e) {
577                 }
578         }
579
580         void setFrequency(String freq) {
581                 try {
582                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
583                 } catch (NumberFormatException e) {
584                 }
585         }
586
587         void setBaud(int baud) {
588                 try {
589                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
590                 } catch (RemoteException e) {
591                 }
592         }
593
594         void setBaud(String baud) {
595                 try {
596                         int     value = Integer.parseInt(baud);
597                         int     rate = AltosLib.ao_telemetry_rate_38400;
598                         switch (value) {
599                         case 2400:
600                                 rate = AltosLib.ao_telemetry_rate_2400;
601                                 break;
602                         case 9600:
603                                 rate = AltosLib.ao_telemetry_rate_9600;
604                                 break;
605                         case 38400:
606                                 rate = AltosLib.ao_telemetry_rate_38400;
607                                 break;
608                         }
609                         setBaud(rate);
610                 } catch (NumberFormatException e) {
611                 }
612         }
613
614         @Override
615         public boolean onOptionsItemSelected(MenuItem item) {
616                 Intent serverIntent = null;
617                 switch (item.getItemId()) {
618                 case R.id.connect_scan:
619                         // Launch the DeviceListActivity to see devices and do scan
620                         serverIntent = new Intent(this, DeviceListActivity.class);
621                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
622                         return true;
623                 case R.id.quit:
624                         Log.d(TAG, "R.id.quit");
625                         stopService(new Intent(AltosDroid.this, TelemetryService.class));
626                         finish();
627                         return true;
628                 case R.id.select_freq:
629                         // Set the TBT radio frequency
630
631                         final String[] frequencies = {
632                                 "Channel 0 (434.550MHz)",
633                                 "Channel 1 (434.650MHz)",
634                                 "Channel 2 (434.750MHz)",
635                                 "Channel 3 (434.850MHz)",
636                                 "Channel 4 (434.950MHz)",
637                                 "Channel 5 (435.050MHz)",
638                                 "Channel 6 (435.150MHz)",
639                                 "Channel 7 (435.250MHz)",
640                                 "Channel 8 (435.350MHz)",
641                                 "Channel 9 (435.450MHz)"
642                         };
643
644                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
645                         builder_freq.setTitle("Pick a frequency");
646                         builder_freq.setItems(frequencies,
647                                          new DialogInterface.OnClickListener() {
648                                                  public void onClick(DialogInterface dialog, int item) {
649                                                          setFrequency(frequencies[item]);
650                                                  }
651                                          });
652                         AlertDialog alert_freq = builder_freq.create();
653                         alert_freq.show();
654                         return true;
655                 case R.id.select_rate:
656                         // Set the TBT baud rate
657
658                         final String[] rates = {
659                                 "38400",
660                                 "9600",
661                                 "2400",
662                         };
663
664                         AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
665                         builder_rate.setTitle("Pick a baud rate");
666                         builder_rate.setItems(rates,
667                                          new DialogInterface.OnClickListener() {
668                                                  public void onClick(DialogInterface dialog, int item) {
669                                                          setBaud(rates[item]);
670                                                  }
671                                          });
672                         AlertDialog alert_rate = builder_rate.create();
673                         alert_rate.show();
674                         return true;
675                 case R.id.change_units:
676                         boolean imperial = AltosPreferences.imperial_units();
677                         AltosPreferences.set_imperial_units(!imperial);
678                         return true;
679                 }
680                 return false;
681         }
682
683 }