altosdroid: Strings and Layout changes
[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 import android.app.Activity;
22 import android.bluetooth.BluetoothAdapter;
23 import android.bluetooth.BluetoothDevice;
24 import android.content.Intent;
25 import android.content.Context;
26 import android.content.ComponentName;
27 import android.content.ServiceConnection;
28 import android.os.IBinder;
29 import android.os.Bundle;
30 import android.os.Handler;
31 import android.os.Message;
32 import android.os.Messenger;
33 import android.os.RemoteException;
34 import android.text.method.ScrollingMovementMethod;
35 import android.util.Log;
36 //import android.view.KeyEvent;
37 import android.view.Menu;
38 import android.view.MenuInflater;
39 import android.view.MenuItem;
40 //import android.view.View;
41 import android.view.Window;
42 //import android.view.View.OnClickListener;
43 //import android.view.inputmethod.EditorInfo;
44 //import android.widget.Button;
45 //import android.widget.EditText;
46 import android.widget.TextView;
47 import android.widget.Toast;
48 import org.altusmetrum.AltosDroid.R;
49
50 /**
51  * This is the main Activity that displays the current chat session.
52  */
53 public class AltosDroid extends Activity {
54         // Debugging
55         private static final String TAG = "AltosDroid";
56         private static final boolean D = true;
57
58         // Message types sent from the TelemetryService Handler
59         public static final int MSG_STATE_CHANGE    = 1;
60         public static final int MSG_DEVNAME         = 2;
61         public static final int MSG_INCOMING_TELEM  = 3;
62         public static final int MSG_TOAST           = 4;
63
64         // Key names received from the TelemetryService Handler
65         public static final String KEY_DEVNAME = "key_devname";
66         public static final String KEY_TOAST   = "key_toast";
67
68         // Intent request codes
69         private static final int REQUEST_CONNECT_DEVICE = 1;
70         private static final int REQUEST_ENABLE_BT      = 2;
71
72         // Layout Views
73         private TextView mTitle;
74         private TextView mSerialView;
75         //private EditText mOutEditText;
76         //private Button mSendButton;
77
78         private boolean mIsBound;
79         Messenger mService = null;
80         final Messenger mMessenger = new Messenger(new IncomingHandler());
81
82         // Name of the connected device
83         private String mConnectedDeviceName = null;
84         // Local Bluetooth adapter
85         private BluetoothAdapter mBluetoothAdapter = null;
86
87
88         // The Handler that gets information back from the Telemetry Service
89         static class IncomingHandler extends Handler {
90                 private final WeakReference<AltosDroid> mAltosDroid;
91                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
92
93                 @Override
94                 public void handleMessage(Message msg) {
95                         AltosDroid ad = mAltosDroid.get();
96                         switch (msg.what) {
97                         case MSG_STATE_CHANGE:
98                                 if(D) Log.i(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
99                                 switch (msg.arg1) {
100                                 case TelemetryService.STATE_CONNECTED:
101                                         ad.mTitle.setText(R.string.title_connected_to);
102                                         ad.mTitle.append(ad.mConnectedDeviceName);
103                                         ad.mSerialView.setText("");
104                                         break;
105                                 case TelemetryService.STATE_CONNECTING:
106                                         ad.mTitle.setText(R.string.title_connecting);
107                                         break;
108                                 case TelemetryService.STATE_READY:
109                                 case TelemetryService.STATE_NONE:
110                                         ad.mTitle.setText(R.string.title_not_connected);
111                                         break;
112                                 }
113                                 break;
114                         case MSG_INCOMING_TELEM:
115                                 byte[] buf = (byte[]) msg.obj;
116                                 // construct a string from the buffer
117                                 String telem = new String(buf);
118                                 ad.mSerialView.append(telem);
119                                 break;
120                         case MSG_DEVNAME:
121                                 // save the connected device's name
122                                 ad.mConnectedDeviceName = msg.getData().getString(KEY_DEVNAME);
123                                 Toast.makeText(ad.getApplicationContext(), "Connected to "
124                                                         + ad.mConnectedDeviceName, Toast.LENGTH_SHORT).show();
125                                 break;
126                         case MSG_TOAST:
127                                 Toast.makeText(
128                                                 ad.getApplicationContext(),
129                                                 msg.getData().getString(KEY_TOAST),
130                                                 Toast.LENGTH_SHORT).show();
131                                 break;
132                         }
133                 }
134         };
135
136
137         private ServiceConnection mConnection = new ServiceConnection() {
138                 public void onServiceConnected(ComponentName className, IBinder service) {
139                         mService = new Messenger(service);
140                         try {
141                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
142                                 msg.replyTo = mMessenger;
143                                 mService.send(msg);
144                         } catch (RemoteException e) {
145                                 // In this case the service has crashed before we could even do anything with it
146                         }
147                 }
148
149                 public void onServiceDisconnected(ComponentName className) {
150                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
151                         mService = null;
152                 }
153         };
154
155
156         @Override
157         public void onCreate(Bundle savedInstanceState) {
158                 super.onCreate(savedInstanceState);
159                 if(D) Log.e(TAG, "+++ ON CREATE +++");
160
161                 // Set up the window layout
162                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
163                 setContentView(R.layout.main);
164                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
165
166                 // Set up the custom title
167                 mTitle = (TextView) findViewById(R.id.title_left_text);
168                 mTitle.setText(R.string.app_name);
169                 mTitle = (TextView) findViewById(R.id.title_right_text);
170
171                 mSerialView = (TextView) findViewById(R.id.in);
172                 mSerialView.setMovementMethod(new ScrollingMovementMethod());
173                 mSerialView.setClickable(false);
174                 mSerialView.setLongClickable(false);
175
176                 // Get local Bluetooth adapter
177                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
178
179                 // If the adapter is null, then Bluetooth is not supported
180                 if (mBluetoothAdapter == null) {
181                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
182                         finish();
183                         return;
184                 }
185
186                 // Start Telemetry Service
187                 startService(new Intent(AltosDroid.this, TelemetryService.class));
188
189                 doBindService();
190         }
191
192         @Override
193         public void onStart() {
194                 super.onStart();
195                 if(D) Log.e(TAG, "++ ON START ++");
196
197                 if (!mBluetoothAdapter.isEnabled()) {
198                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
199                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
200                 } else {
201                         //if (mChatService == null) setupChat();
202                 }
203         }
204
205         @Override
206         public synchronized void onResume() {
207                 super.onResume();
208                 if(D) Log.e(TAG, "+ ON RESUME +");
209
210                 // Performing this check in onResume() covers the case in which BT was
211                 // not enabled during onStart(), so we were paused to enable it...
212                 // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
213                 //if (mChatService != null) {
214                         // Only if the state is STATE_NONE, do we know that we haven't started already
215                         //if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
216                         // Start the Bluetooth chat services
217                         //mChatService.start();
218                         //}
219                 //}
220         }
221
222         @Override
223         public synchronized void onPause() {
224                 super.onPause();
225                 if(D) Log.e(TAG, "- ON PAUSE -");
226         }
227
228         @Override
229         public void onStop() {
230                 super.onStop();
231                 if(D) Log.e(TAG, "-- ON STOP --");
232         }
233
234         @Override
235         public void onDestroy() {
236                 super.onDestroy();
237
238                 doUnbindService();
239
240                 if(D) Log.e(TAG, "--- ON DESTROY ---");
241         }
242
243
244
245 /*
246         private void setupChat() {
247                 Log.d(TAG, "setupChat()");
248
249                 // Initialize the compose field with a listener for the return key
250                 mOutEditText = (EditText) findViewById(R.id.edit_text_out);
251                 mOutEditText.setOnEditorActionListener(mWriteListener);
252
253                 // Initialize the send button with a listener that for click events
254                 mSendButton = (Button) findViewById(R.id.button_send);
255                 mSendButton.setOnClickListener(new OnClickListener() {
256                         public void onClick(View v) {
257                                 // Send a message using content of the edit text widget
258                                 TextView view = (TextView) findViewById(R.id.edit_text_out);
259                                 String message = view.getText().toString();
260                                 sendMessage(message);
261                         }
262                 });
263
264                 // Initialize the BluetoothChatService to perform bluetooth connections
265                 mChatService = new BluetoothChatService(this, mHandler);
266
267                 // Initialize the buffer for outgoing messages
268                 mOutStringBuffer = new StringBuffer("");
269         }
270 */
271
272         /**
273          * Sends a message.
274          * @param message  A string of text to send.
275          */
276         /*
277         private void sendMessage(String message) {
278                 // Check that we're actually connected before trying anything
279                 if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
280                         Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
281                         return;
282                 }
283
284                 // Check that there's actually something to send
285                 if (message.length() > 0) {
286                         // Get the message bytes and tell the BluetoothChatService to write
287                         byte[] send = message.getBytes();
288                         mChatService.write(send);
289
290                         // Reset out string buffer to zero and clear the edit text field
291                         mOutStringBuffer.setLength(0);
292                         mOutEditText.setText(mOutStringBuffer);
293                 }
294         }
295
296
297         // The action listener for the EditText widget, to listen for the return key
298         private TextView.OnEditorActionListener mWriteListener =
299                 new TextView.OnEditorActionListener() {
300                 public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
301                         // If the action is a key-up event on the return key, send the message
302                         if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
303                                 String message = view.getText().toString();
304                                 sendMessage(message);
305                         }
306                         if(D) Log.i(TAG, "END onEditorAction");
307                         return true;
308                 }
309         };
310         */
311
312         public void onActivityResult(int requestCode, int resultCode, Intent data) {
313                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
314                 switch (requestCode) {
315                 case REQUEST_CONNECT_DEVICE:
316                         // When DeviceListActivity returns with a device to connect to
317                         if (resultCode == Activity.RESULT_OK) {
318                                 connectDevice(data);
319                         }
320                         break;
321                 case REQUEST_ENABLE_BT:
322                         // When the request to enable Bluetooth returns
323                         if (resultCode == Activity.RESULT_OK) {
324                                 // Bluetooth is now enabled, so set up a chat session
325                                 //setupChat();
326                         } else {
327                                 // User did not enable Bluetooth or an error occured
328                                 Log.d(TAG, "BT not enabled");
329                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
330                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
331                                 finish();
332                         }
333                 }
334         }
335
336         private void connectDevice(Intent data) {
337                 // Get the device MAC address
338                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
339                 // Get the BLuetoothDevice object
340                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
341                 // Attempt to connect to the device
342                 try {
343                         //Message msg = Message.obtain(null, TelemetryService.MSG_CONNECT_TELEBT);
344                         //msg.obj = device;
345                         //mService.send(msg);
346                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
347                 } catch (RemoteException e) {
348                         e.printStackTrace();
349                 }
350         }
351
352
353         @Override
354         public boolean onCreateOptionsMenu(Menu menu) {
355                 MenuInflater inflater = getMenuInflater();
356                 inflater.inflate(R.menu.option_menu, menu);
357                 return true;
358         }
359
360         @Override
361         public boolean onOptionsItemSelected(MenuItem item) {
362                 Intent serverIntent = null;
363                 switch (item.getItemId()) {
364                 case R.id.connect_scan:
365                         // Launch the DeviceListActivity to see devices and do scan
366                         serverIntent = new Intent(this, DeviceListActivity.class);
367                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
368                         return true;
369                 }
370                 return false;
371         }
372
373
374         void doBindService() {
375                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
376                 mIsBound = true;
377         }
378
379         void doUnbindService() {
380                 if (mIsBound) {
381                         // If we have received the service, and hence registered with it, then now is the time to unregister.
382                         if (mService != null) {
383                                 try {
384                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
385                                         msg.replyTo = mMessenger;
386                                         mService.send(msg);
387                                 } catch (RemoteException e) {
388                                         // There is nothing special we need to do if the service has crashed.
389                                 }
390                         }
391                         // Detach our existing connection.
392                         unbindService(mConnection);
393                         mIsBound = false;
394                 }
395         }
396
397 }