altosdroid: do service start/bind/unbind in start/stop, not create/destroy.
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / AltosDroid.java
1 /*
2  * Copyright © 2012 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
22 import android.app.Activity;
23 import android.bluetooth.BluetoothAdapter;
24 import android.bluetooth.BluetoothDevice;
25 import android.content.Intent;
26 import android.content.Context;
27 import android.content.ComponentName;
28 import android.content.ServiceConnection;
29 import android.os.IBinder;
30 import android.os.Bundle;
31 import android.os.Handler;
32 import android.os.Message;
33 import android.os.Messenger;
34 import android.os.RemoteException;
35 import android.speech.tts.TextToSpeech;
36 import android.speech.tts.TextToSpeech.OnInitListener;
37 import android.text.method.ScrollingMovementMethod;
38 import android.util.Log;
39 import android.view.Menu;
40 import android.view.MenuInflater;
41 import android.view.MenuItem;
42 import android.view.Window;
43 import android.widget.TextView;
44 import android.widget.Toast;
45
46 import org.altusmetrum.AltosLib.*;
47
48 /**
49  * This is the main Activity that displays the current chat session.
50  */
51 public class AltosDroid extends Activity {
52         // Debugging
53         private static final String TAG = "AltosDroid";
54         private static final boolean D = true;
55
56         // Message types received by our Handler
57         public static final int MSG_STATE_CHANGE    = 1;
58         public static final int MSG_TELEMETRY       = 2;
59
60         // Intent request codes
61         private static final int REQUEST_CONNECT_DEVICE = 1;
62         private static final int REQUEST_ENABLE_BT      = 2;
63
64         // Layout Views
65         private TextView mTitle;
66         private TextView mSerialView;
67
68         // Service
69         private boolean mIsBound   = false;
70         private Messenger mService = null;
71         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
72
73         // TeleBT Config data
74         private AltosConfigData mConfigData = null;
75         // Local Bluetooth adapter
76         private BluetoothAdapter mBluetoothAdapter = null;
77
78         // Text to Speech
79         private TextToSpeech tts    = null;
80         private boolean tts_enabled = false;
81
82         // The Handler that gets information back from the Telemetry Service
83         static class IncomingHandler extends Handler {
84                 private final WeakReference<AltosDroid> mAltosDroid;
85                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
86
87                 @Override
88                 public void handleMessage(Message msg) {
89                         AltosDroid ad = mAltosDroid.get();
90                         switch (msg.what) {
91                         case MSG_STATE_CHANGE:
92                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
93                                 switch (msg.arg1) {
94                                 case TelemetryService.STATE_CONNECTED:
95                                         ad.mConfigData = (AltosConfigData) msg.obj;
96                                         String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
97                                         ad.mTitle.setText(R.string.title_connected_to);
98                                         ad.mTitle.append(str);
99                                         Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
100                                         break;
101                                 case TelemetryService.STATE_CONNECTING:
102                                         ad.mTitle.setText(R.string.title_connecting);
103                                         break;
104                                 case TelemetryService.STATE_READY:
105                                 case TelemetryService.STATE_NONE:
106                                         ad.mConfigData = null;
107                                         ad.mTitle.setText(R.string.title_not_connected);
108                                         ad.mSerialView.setText("");
109                                         break;
110                                 }
111                                 break;
112                         case MSG_TELEMETRY:
113                                 //byte[] buf = (byte[]) msg.obj;
114                                 // construct a string from the buffer
115                                 //String telem = new String(buf);
116                                 //ad.mSerialView.append(telem);
117                                 break;
118                         }
119                 }
120         };
121
122
123         private ServiceConnection mConnection = new ServiceConnection() {
124                 public void onServiceConnected(ComponentName className, IBinder service) {
125                         mService = new Messenger(service);
126                         try {
127                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
128                                 msg.replyTo = mMessenger;
129                                 mService.send(msg);
130                         } catch (RemoteException e) {
131                                 // In this case the service has crashed before we could even do anything with it
132                         }
133                 }
134
135                 public void onServiceDisconnected(ComponentName className) {
136                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
137                         mService = null;
138                 }
139         };
140
141
142         void doBindService() {
143                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
144                 mIsBound = true;
145         }
146
147         void doUnbindService() {
148                 if (mIsBound) {
149                         // If we have received the service, and hence registered with it, then now is the time to unregister.
150                         if (mService != null) {
151                                 try {
152                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
153                                         msg.replyTo = mMessenger;
154                                         mService.send(msg);
155                                 } catch (RemoteException e) {
156                                         // There is nothing special we need to do if the service has crashed.
157                                 }
158                         }
159                         // Detach our existing connection.
160                         unbindService(mConnection);
161                         mIsBound = false;
162                 }
163         }
164
165
166         @Override
167         public void onCreate(Bundle savedInstanceState) {
168                 super.onCreate(savedInstanceState);
169                 if(D) Log.e(TAG, "+++ ON CREATE +++");
170
171                 // Set up the window layout
172                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
173                 setContentView(R.layout.main);
174                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
175
176                 // Set up the custom title
177                 mTitle = (TextView) findViewById(R.id.title_left_text);
178                 mTitle.setText(R.string.app_name);
179                 mTitle = (TextView) findViewById(R.id.title_right_text);
180
181                 // Set up the temporary Text View
182                 mSerialView = (TextView) findViewById(R.id.in);
183                 mSerialView.setMovementMethod(new ScrollingMovementMethod());
184                 mSerialView.setClickable(false);
185                 mSerialView.setLongClickable(false);
186
187                 // Get local Bluetooth adapter
188                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
189
190                 // If the adapter is null, then Bluetooth is not supported
191                 if (mBluetoothAdapter == null) {
192                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
193                         finish();
194                         return;
195                 }
196
197                 // Enable Text to Speech
198                 tts = new TextToSpeech(this, new OnInitListener() {
199                         public void onInit(int status) {
200                                 if (status == TextToSpeech.SUCCESS) tts_enabled = true;
201                                 if (tts_enabled) tts.speak("AltosDroid ready", TextToSpeech.QUEUE_ADD, null );
202                         }
203                 });
204
205         }
206
207         @Override
208         public void onStart() {
209                 super.onStart();
210                 if(D) Log.e(TAG, "++ ON START ++");
211
212                 if (!mBluetoothAdapter.isEnabled()) {
213                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
214                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
215                 }
216
217                 // Start Telemetry Service
218                 startService(new Intent(AltosDroid.this, TelemetryService.class));
219
220                 doBindService();
221         }
222
223         @Override
224         public synchronized void onResume() {
225                 super.onResume();
226                 if(D) Log.e(TAG, "+ ON RESUME +");
227         }
228
229         @Override
230         public synchronized void onPause() {
231                 super.onPause();
232                 if(D) Log.e(TAG, "- ON PAUSE -");
233         }
234
235         @Override
236         public void onStop() {
237                 super.onStop();
238                 if(D) Log.e(TAG, "-- ON STOP --");
239
240                 doUnbindService();
241         }
242
243         @Override
244         public void onDestroy() {
245                 super.onDestroy();
246                 if(D) Log.e(TAG, "--- ON DESTROY ---");
247
248                 if (tts != null) tts.shutdown();
249         }
250
251
252
253
254         public void onActivityResult(int requestCode, int resultCode, Intent data) {
255                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
256                 switch (requestCode) {
257                 case REQUEST_CONNECT_DEVICE:
258                         // When DeviceListActivity returns with a device to connect to
259                         if (resultCode == Activity.RESULT_OK) {
260                                 connectDevice(data);
261                         }
262                         break;
263                 case REQUEST_ENABLE_BT:
264                         // When the request to enable Bluetooth returns
265                         if (resultCode == Activity.RESULT_OK) {
266                                 // Bluetooth is now enabled, so set up a chat session
267                                 //setupChat();
268                         } else {
269                                 // User did not enable Bluetooth or an error occured
270                                 Log.e(TAG, "BT not enabled");
271                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
272                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
273                                 finish();
274                         }
275                         break;
276                 }
277         }
278
279         private void connectDevice(Intent data) {
280                 // Get the device MAC address
281                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
282                 // Get the BLuetoothDevice object
283                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
284                 // Attempt to connect to the device
285                 try {
286                         if (D) Log.d(TAG, "Connecting to " + device.getName());
287                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
288                 } catch (RemoteException e) {
289                 }
290         }
291
292         @Override
293         public boolean onCreateOptionsMenu(Menu menu) {
294                 MenuInflater inflater = getMenuInflater();
295                 inflater.inflate(R.menu.option_menu, menu);
296                 return true;
297         }
298
299         @Override
300         public boolean onOptionsItemSelected(MenuItem item) {
301                 Intent serverIntent = null;
302                 switch (item.getItemId()) {
303                 case R.id.connect_scan:
304                         // Launch the DeviceListActivity to see devices and do scan
305                         serverIntent = new Intent(this, DeviceListActivity.class);
306                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
307                         return true;
308                 }
309                 return false;
310         }
311
312 }