2 * Copyright © 2012 Mike Beattie <mike@ethernal.org>
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.
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.
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.
18 package org.altusmetrum.AltosDroid;
20 import java.lang.ref.WeakReference;
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.KeyEvent;
40 import android.view.Menu;
41 import android.view.MenuInflater;
42 import android.view.MenuItem;
43 //import android.view.View;
44 import android.view.Window;
45 //import android.view.View.OnClickListener;
46 //import android.view.inputmethod.EditorInfo;
47 //import android.widget.Button;
48 //import android.widget.EditText;
49 import android.widget.TextView;
50 import android.widget.Toast;
51 //import org.altusmetrum.AltosDroid.R;
54 * This is the main Activity that displays the current chat session.
56 public class AltosDroid extends Activity {
58 private static final String TAG = "AltosDroid";
59 private static final boolean D = true;
61 // Message types sent from the TelemetryService Handler
62 public static final int MSG_STATE_CHANGE = 1;
63 public static final int MSG_DEVNAME = 2;
64 public static final int MSG_TOAST = 3;
65 public static final int MSG_DEVCONFIG = 4;
66 public static final int MSG_TELEMETRY = 5;
68 // Intent request codes
69 private static final int REQUEST_CONNECT_DEVICE = 1;
70 private static final int REQUEST_ENABLE_BT = 2;
73 private TextView mTitle;
74 private TextView mSerialView;
75 //private EditText mOutEditText;
76 //private Button mSendButton;
78 private boolean mIsBound;
79 Messenger mService = null;
80 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
82 // Name of the connected device
83 private String mConnectedDeviceName = null;
84 // Local Bluetooth adapter
85 private BluetoothAdapter mBluetoothAdapter = null;
87 private TextToSpeech tts;
88 private boolean tts_enabled = false;
90 // The Handler that gets information back from the Telemetry Service
91 static class IncomingHandler extends Handler {
92 private final WeakReference<AltosDroid> mAltosDroid;
93 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
96 public void handleMessage(Message msg) {
97 AltosDroid ad = mAltosDroid.get();
99 case MSG_STATE_CHANGE:
100 if(D) Log.i(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
102 case TelemetryService.STATE_CONNECTED:
103 ad.mTitle.setText(R.string.title_connected_to);
104 ad.mTitle.append(ad.mConnectedDeviceName);
105 ad.mSerialView.setText("");
107 case TelemetryService.STATE_CONNECTING:
108 ad.mTitle.setText(R.string.title_connecting);
110 case TelemetryService.STATE_READY:
111 case TelemetryService.STATE_NONE:
112 ad.mTitle.setText(R.string.title_not_connected);
118 //byte[] buf = (byte[]) msg.obj;
119 // construct a string from the buffer
120 //String telem = new String(buf);
121 //ad.mSerialView.append(telem);
124 // save the connected device's name
125 ad.mConnectedDeviceName = (String) msg.obj;
126 if (ad.mConnectedDeviceName != null)
127 Toast.makeText(ad.getApplicationContext(), "Connected to "
128 + ad.mConnectedDeviceName, Toast.LENGTH_SHORT).show();
132 ad.getApplicationContext(),
134 Toast.LENGTH_SHORT).show();
141 private ServiceConnection mConnection = new ServiceConnection() {
142 public void onServiceConnected(ComponentName className, IBinder service) {
143 mService = new Messenger(service);
145 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
146 msg.replyTo = mMessenger;
148 } catch (RemoteException e) {
149 // In this case the service has crashed before we could even do anything with it
153 public void onServiceDisconnected(ComponentName className) {
154 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
161 public void onCreate(Bundle savedInstanceState) {
162 super.onCreate(savedInstanceState);
163 if(D) Log.e(TAG, "+++ ON CREATE +++");
165 // Set up the window layout
166 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
167 setContentView(R.layout.main);
168 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
170 // Set up the custom title
171 mTitle = (TextView) findViewById(R.id.title_left_text);
172 mTitle.setText(R.string.app_name);
173 mTitle = (TextView) findViewById(R.id.title_right_text);
175 mSerialView = (TextView) findViewById(R.id.in);
176 mSerialView.setMovementMethod(new ScrollingMovementMethod());
177 mSerialView.setClickable(false);
178 mSerialView.setLongClickable(false);
180 // Get local Bluetooth adapter
181 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
183 // If the adapter is null, then Bluetooth is not supported
184 if (mBluetoothAdapter == null) {
185 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
190 // Enable Text to Speech
191 tts = new TextToSpeech(this, new OnInitListener() {
192 public void onInit(int status) {
193 if (status == TextToSpeech.SUCCESS) tts_enabled = true;
194 if (tts_enabled) tts.speak("AltosDroid ready", TextToSpeech.QUEUE_ADD, null );
198 // Start Telemetry Service
199 startService(new Intent(AltosDroid.this, TelemetryService.class));
205 public void onStart() {
207 if(D) Log.e(TAG, "++ ON START ++");
209 if (!mBluetoothAdapter.isEnabled()) {
210 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
211 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
213 //if (mChatService == null) setupChat();
218 public synchronized void onResume() {
220 if(D) Log.e(TAG, "+ ON RESUME +");
222 // Performing this check in onResume() covers the case in which BT was
223 // not enabled during onStart(), so we were paused to enable it...
224 // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
225 //if (mChatService != null) {
226 // Only if the state is STATE_NONE, do we know that we haven't started already
227 //if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
228 // Start the Bluetooth chat services
229 //mChatService.start();
235 public synchronized void onPause() {
237 if(D) Log.e(TAG, "- ON PAUSE -");
241 public void onStop() {
243 if(D) Log.e(TAG, "-- ON STOP --");
247 public void onDestroy() {
252 if (tts != null) tts.shutdown();
254 if(D) Log.e(TAG, "--- ON DESTROY ---");
260 private void setupChat() {
261 Log.d(TAG, "setupChat()");
263 // Initialize the compose field with a listener for the return key
264 mOutEditText = (EditText) findViewById(R.id.edit_text_out);
265 mOutEditText.setOnEditorActionListener(mWriteListener);
267 // Initialize the send button with a listener that for click events
268 mSendButton = (Button) findViewById(R.id.button_send);
269 mSendButton.setOnClickListener(new OnClickListener() {
270 public void onClick(View v) {
271 // Send a message using content of the edit text widget
272 TextView view = (TextView) findViewById(R.id.edit_text_out);
273 String message = view.getText().toString();
274 sendMessage(message);
278 // Initialize the BluetoothChatService to perform bluetooth connections
279 mChatService = new BluetoothChatService(this, mHandler);
281 // Initialize the buffer for outgoing messages
282 mOutStringBuffer = new StringBuffer("");
288 * @param message A string of text to send.
291 private void sendMessage(String message) {
292 // Check that we're actually connected before trying anything
293 if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
294 Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
298 // Check that there's actually something to send
299 if (message.length() > 0) {
300 // Get the message bytes and tell the BluetoothChatService to write
301 byte[] send = message.getBytes();
302 mChatService.write(send);
304 // Reset out string buffer to zero and clear the edit text field
305 mOutStringBuffer.setLength(0);
306 mOutEditText.setText(mOutStringBuffer);
311 // The action listener for the EditText widget, to listen for the return key
312 private TextView.OnEditorActionListener mWriteListener =
313 new TextView.OnEditorActionListener() {
314 public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
315 // If the action is a key-up event on the return key, send the message
316 if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
317 String message = view.getText().toString();
318 sendMessage(message);
320 if(D) Log.i(TAG, "END onEditorAction");
326 public void onActivityResult(int requestCode, int resultCode, Intent data) {
327 if(D) Log.d(TAG, "onActivityResult " + resultCode);
328 switch (requestCode) {
329 case REQUEST_CONNECT_DEVICE:
330 // When DeviceListActivity returns with a device to connect to
331 if (resultCode == Activity.RESULT_OK) {
335 case REQUEST_ENABLE_BT:
336 // When the request to enable Bluetooth returns
337 if (resultCode == Activity.RESULT_OK) {
338 // Bluetooth is now enabled, so set up a chat session
341 // User did not enable Bluetooth or an error occured
342 Log.d(TAG, "BT not enabled");
343 stopService(new Intent(AltosDroid.this, TelemetryService.class));
344 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
351 private void connectDevice(Intent data) {
352 // Get the device MAC address
353 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
354 // Get the BLuetoothDevice object
355 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
356 // Attempt to connect to the device
358 //Message msg = Message.obtain(null, TelemetryService.MSG_CONNECT_TELEBT);
360 //mService.send(msg);
361 if (D) Log.i(TAG, "Connecting to " + device.getName());
362 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
363 } catch (RemoteException e) {
369 public boolean onCreateOptionsMenu(Menu menu) {
370 MenuInflater inflater = getMenuInflater();
371 inflater.inflate(R.menu.option_menu, menu);
376 public boolean onOptionsItemSelected(MenuItem item) {
377 Intent serverIntent = null;
378 switch (item.getItemId()) {
379 case R.id.connect_scan:
380 // Launch the DeviceListActivity to see devices and do scan
381 serverIntent = new Intent(this, DeviceListActivity.class);
382 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
389 void doBindService() {
390 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
394 void doUnbindService() {
396 // If we have received the service, and hence registered with it, then now is the time to unregister.
397 if (mService != null) {
399 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
400 msg.replyTo = mMessenger;
402 } catch (RemoteException e) {
403 // There is nothing special we need to do if the service has crashed.
406 // Detach our existing connection.
407 unbindService(mConnection);