altosdroid: Explicitly disconnect BT on termination or 'disconnect'
[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_6.*;
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                         if (telemetry_state.address != null)
211                                 mTitle.setText(String.format("Connecting to %s...", telemetry_state.address.name));
212                         else
213                                 mTitle.setText("Connecting to something...");
214                         break;
215                 case TelemetryState.CONNECT_DISCONNECTED:
216                 case TelemetryState.CONNECT_NONE:
217                         mTitle.setText(R.string.title_not_connected);
218                         break;
219                 }
220         }
221
222         void start_timer() {
223                 if (timer == null) {
224                         timer = new Timer();
225                         timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
226                 }
227         }
228
229         void stop_timer() {
230                 if (timer != null) {
231                         timer.cancel();
232                         timer.purge();
233                         timer = null;
234                 }
235         }
236
237         boolean registered_units_listener;
238
239         void update_state(TelemetryState telemetry_state) {
240
241                 if (!registered_units_listener) {
242                         registered_units_listener = true;
243                         AltosPreferences.register_units_listener(this);
244                 }
245
246                 update_title(telemetry_state);
247                 update_ui(telemetry_state.state, telemetry_state.location);
248                 if (telemetry_state.connect == TelemetryState.CONNECT_CONNECTED)
249                         start_timer();
250         }
251
252         boolean same_string(String a, String b) {
253                 if (a == null) {
254                         if (b == null)
255                                 return true;
256                         return false;
257                 } else {
258                         if (b == null)
259                                 return false;
260                         return a.equals(b);
261                 }
262         }
263
264         void update_age() {
265                 if (saved_state != null)
266                         mAgeView.setText(String.format("%d", (System.currentTimeMillis() - saved_state.received_time + 500) / 1000));
267         }
268
269         void update_ui(AltosState state, Location location) {
270
271                 int prev_state = AltosLib.ao_flight_invalid;
272
273                 AltosGreatCircle from_receiver = null;
274
275                 if (saved_state != null)
276                         prev_state = saved_state.state;
277
278                 if (state != null) {
279                         if (state.state == AltosLib.ao_flight_stateless) {
280                                 boolean prev_locked = false;
281                                 boolean locked = false;
282
283                                 if(state.gps != null)
284                                         locked = state.gps.locked;
285                                 if (saved_state != null && saved_state.gps != null)
286                                         prev_locked = saved_state.gps.locked;
287                                 if (prev_locked != locked) {
288                                         String currentTab = mTabHost.getCurrentTabTag();
289                                         if (locked) {
290                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
291                                         } else {
292                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
293                                         }
294                                 }
295                         } else {
296                                 if (prev_state != state.state) {
297                                         String currentTab = mTabHost.getCurrentTabTag();
298                                         switch (state.state) {
299                                         case AltosLib.ao_flight_boost:
300                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
301                                                 break;
302                                         case AltosLib.ao_flight_drogue:
303                                                 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
304                                                 break;
305                                         case AltosLib.ao_flight_landed:
306                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
307                                                 break;
308                                         case AltosLib.ao_flight_stateless:
309                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
310                                                 break;
311                                         }
312                                 }
313                         }
314
315                         if (location != null && state.gps != null && state.gps.locked) {
316                                 double altitude = 0;
317                                 if (location.hasAltitude())
318                                         altitude = location.getAltitude();
319                                 from_receiver = new AltosGreatCircle(location.getLatitude(),
320                                                                      location.getLongitude(),
321                                                                      altitude,
322                                                                      state.gps.lat,
323                                                                      state.gps.lon,
324                                                                      state.gps.alt);
325                         }
326
327                         if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
328                                 mCallsignView.setText(state.callsign);
329                         }
330                         if (saved_state == null || state.serial != saved_state.serial) {
331                                 mSerialView.setText(String.format("%d", state.serial));
332                         }
333                         if (saved_state == null || state.flight != saved_state.flight) {
334                                 if (state.flight == AltosLib.MISSING)
335                                         mFlightView.setText("");
336                                 else
337                                         mFlightView.setText(String.format("%d", state.flight));
338                         }
339                         if (saved_state == null || state.state != saved_state.state) {
340                                 if (state.state == AltosLib.ao_flight_stateless) {
341                                         mStateLayout.setVisibility(View.GONE);
342                                 } else {
343                                         mStateView.setText(state.state_name());
344                                         mStateLayout.setVisibility(View.VISIBLE);
345                                 }
346                         }
347                         if (saved_state == null || state.rssi != saved_state.rssi) {
348                                 mRSSIView.setText(String.format("%d", state.rssi));
349                         }
350                 }
351
352                 for (AltosDroidTab mTab : mTabs)
353                         mTab.update_ui(state, from_receiver, location, mTab == mTabsAdapter.currentItem());
354
355                 if (state != null)
356                         mAltosVoice.tell(state, from_receiver);
357
358                 saved_state = state;
359         }
360
361         private void onTimerTick() {
362                 try {
363                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
364                 } catch (RemoteException e) {
365                 }
366         }
367
368         static String pos(double p, String pos, String neg) {
369                 String  h = pos;
370                 if (p == AltosLib.MISSING)
371                         return "";
372                 if (p < 0) {
373                         h = neg;
374                         p = -p;
375                 }
376                 int deg = (int) Math.floor(p);
377                 double min = (p - Math.floor(p)) * 60.0;
378                 return String.format("%d°%9.4f\" %s", deg, min, h);
379         }
380
381         static String number(String format, double value) {
382                 if (value == AltosLib.MISSING)
383                         return "";
384                 return String.format(format, value);
385         }
386
387         static String integer(String format, int value) {
388                 if (value == AltosLib.MISSING)
389                         return "";
390                 return String.format(format, value);
391         }
392
393         @Override
394         public void onCreate(Bundle savedInstanceState) {
395                 super.onCreate(savedInstanceState);
396                 if(D) Log.e(TAG, "+++ ON CREATE +++");
397
398                 // Get local Bluetooth adapter
399                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
400
401                 // If the adapter is null, then Bluetooth is not supported
402                 if (mBluetoothAdapter == null) {
403                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
404                         finish();
405                 }
406
407                 fm = getSupportFragmentManager();
408
409                 // Set up the window layout
410                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
411                 setContentView(R.layout.altosdroid);
412                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
413
414                 // Create the Tabs and ViewPager
415                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
416                 mTabHost.setup();
417
418                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
419                 mViewPager.setOffscreenPageLimit(4);
420
421                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
422
423                 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
424                 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
425                 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
426                 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
427                 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
428
429
430                 // Scale the size of the Tab bar for different screen densities
431                 // This probably won't be needed when we start supporting ICS+ tabs.
432                 DisplayMetrics metrics = new DisplayMetrics();
433                 getWindowManager().getDefaultDisplay().getMetrics(metrics);
434                 int density = metrics.densityDpi;
435
436                 if (density==DisplayMetrics.DENSITY_XHIGH)
437                         tabHeight = 65;
438                 else if (density==DisplayMetrics.DENSITY_HIGH)
439                         tabHeight = 45;
440                 else if (density==DisplayMetrics.DENSITY_MEDIUM)
441                         tabHeight = 35;
442                 else if (density==DisplayMetrics.DENSITY_LOW)
443                         tabHeight = 25;
444                 else
445                         tabHeight = 65;
446
447                 for (int i = 0; i < 5; i++)
448                         mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;
449
450                 // Set up the custom title
451                 mTitle = (TextView) findViewById(R.id.title_left_text);
452                 mTitle.setText(R.string.app_name);
453                 mTitle = (TextView) findViewById(R.id.title_right_text);
454
455                 // Display the Version
456                 mVersion = (TextView) findViewById(R.id.version);
457                 mVersion.setText("Version: " + BuildInfo.version +
458                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
459                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
460
461                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
462                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
463                 mSerialView    = (TextView) findViewById(R.id.serial_value);
464                 mFlightView    = (TextView) findViewById(R.id.flight_value);
465                 mStateLayout   = (RelativeLayout) findViewById(R.id.state_container);
466                 mStateView     = (TextView) findViewById(R.id.state_value);
467                 mAgeView       = (TextView) findViewById(R.id.age_value);
468
469                 mAltosVoice = new AltosVoice(this);
470         }
471
472         @Override
473         public void onStart() {
474                 super.onStart();
475                 if(D) Log.e(TAG, "++ ON START ++");
476
477                 // Start Telemetry Service
478                 startService(new Intent(AltosDroid.this, TelemetryService.class));
479
480                 if (!mBluetoothAdapter.isEnabled()) {
481                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
482                         startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
483                 }
484
485                 doBindService();
486
487         }
488
489         @Override
490         public void onResume() {
491                 super.onResume();
492                 if(D) Log.e(TAG, "+ ON RESUME +");
493         }
494
495         @Override
496         public void onPause() {
497                 super.onPause();
498                 if(D) Log.e(TAG, "- ON PAUSE -");
499         }
500
501         @Override
502         public void onStop() {
503                 super.onStop();
504                 if(D) Log.e(TAG, "-- ON STOP --");
505
506                 doUnbindService();
507         }
508
509         @Override
510         public void onDestroy() {
511                 super.onDestroy();
512                 if(D) Log.e(TAG, "--- ON DESTROY ---");
513
514                 if (mAltosVoice != null) mAltosVoice.stop();
515                 stop_timer();
516         }
517
518         public void onActivityResult(int requestCode, int resultCode, Intent data) {
519                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
520                 switch (requestCode) {
521                 case REQUEST_CONNECT_DEVICE:
522                         // When DeviceListActivity returns with a device to connect to
523                         if (resultCode == Activity.RESULT_OK) {
524                                 connectDevice(data);
525                         }
526                         break;
527                 case REQUEST_ENABLE_BT:
528                         // When the request to enable Bluetooth returns
529                         if (resultCode == Activity.RESULT_OK) {
530                                 // Bluetooth is now enabled, so set up a chat session
531                                 //setupChat();
532                         } else {
533                                 // User did not enable Bluetooth or an error occured
534                                 Log.e(TAG, "BT not enabled");
535                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
536                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
537                                 finish();
538                         }
539                         break;
540                 }
541         }
542
543         private void connectDevice(Intent data) {
544                 // Attempt to connect to the device
545                 try {
546                         String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
547                         String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
548
549                         if (D) Log.d(TAG, "Connecting to " + address + name);
550                         DeviceAddress   a = new DeviceAddress(address, name);
551                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
552                 } catch (RemoteException e) {
553                 }
554         }
555
556         private void disconnectDevice() {
557                 try {
558                         mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
559                 } catch (RemoteException e) {
560                 }
561         }
562
563         @Override
564         public boolean onCreateOptionsMenu(Menu menu) {
565                 MenuInflater inflater = getMenuInflater();
566                 inflater.inflate(R.menu.option_menu, menu);
567                 return true;
568         }
569
570         void setFrequency(double freq) {
571                 try {
572                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
573                 } catch (RemoteException e) {
574                 }
575         }
576
577         void setFrequency(String freq) {
578                 try {
579                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
580                 } catch (NumberFormatException e) {
581                 }
582         }
583
584         void setBaud(int baud) {
585                 try {
586                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
587                 } catch (RemoteException e) {
588                 }
589         }
590
591         void setBaud(String baud) {
592                 try {
593                         int     value = Integer.parseInt(baud);
594                         int     rate = AltosLib.ao_telemetry_rate_38400;
595                         switch (value) {
596                         case 2400:
597                                 rate = AltosLib.ao_telemetry_rate_2400;
598                                 break;
599                         case 9600:
600                                 rate = AltosLib.ao_telemetry_rate_9600;
601                                 break;
602                         case 38400:
603                                 rate = AltosLib.ao_telemetry_rate_38400;
604                                 break;
605                         }
606                         setBaud(rate);
607                 } catch (NumberFormatException e) {
608                 }
609         }
610
611         @Override
612         public boolean onOptionsItemSelected(MenuItem item) {
613                 Intent serverIntent = null;
614                 switch (item.getItemId()) {
615                 case R.id.connect_scan:
616                         // Launch the DeviceListActivity to see devices and do scan
617                         serverIntent = new Intent(this, DeviceListActivity.class);
618                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
619                         return true;
620                 case R.id.disconnect:
621                         /* Disconnect the bluetooth device
622                          */
623                         disconnectDevice();
624                         return true;
625                 case R.id.quit:
626                         Log.d(TAG, "R.id.quit");
627                         disconnectDevice();
628                         finish();
629                         return true;
630                 case R.id.select_freq:
631                         // Set the TBT radio frequency
632
633                         final String[] frequencies = {
634                                 "Channel 0 (434.550MHz)",
635                                 "Channel 1 (434.650MHz)",
636                                 "Channel 2 (434.750MHz)",
637                                 "Channel 3 (434.850MHz)",
638                                 "Channel 4 (434.950MHz)",
639                                 "Channel 5 (435.050MHz)",
640                                 "Channel 6 (435.150MHz)",
641                                 "Channel 7 (435.250MHz)",
642                                 "Channel 8 (435.350MHz)",
643                                 "Channel 9 (435.450MHz)"
644                         };
645
646                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
647                         builder_freq.setTitle("Pick a frequency");
648                         builder_freq.setItems(frequencies,
649                                          new DialogInterface.OnClickListener() {
650                                                  public void onClick(DialogInterface dialog, int item) {
651                                                          setFrequency(frequencies[item]);
652                                                  }
653                                          });
654                         AlertDialog alert_freq = builder_freq.create();
655                         alert_freq.show();
656                         return true;
657                 case R.id.select_rate:
658                         // Set the TBT baud rate
659
660                         final String[] rates = {
661                                 "38400",
662                                 "9600",
663                                 "2400",
664                         };
665
666                         AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
667                         builder_rate.setTitle("Pick a baud rate");
668                         builder_rate.setItems(rates,
669                                          new DialogInterface.OnClickListener() {
670                                                  public void onClick(DialogInterface dialog, int item) {
671                                                          setBaud(rates[item]);
672                                                  }
673                                          });
674                         AlertDialog alert_rate = builder_rate.create();
675                         alert_rate.show();
676                         return true;
677                 case R.id.change_units:
678                         boolean imperial = AltosPreferences.imperial_units();
679                         AltosPreferences.set_imperial_units(!imperial);
680                         return true;
681                 }
682                 return false;
683         }
684
685 }