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;
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;
51 * This is the main Activity that displays the current chat session.
53 public class AltosDroid extends Activity {
55 private static final String TAG = "AltosDroid";
56 private static final boolean D = true;
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;
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";
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;
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); }
94 public void handleMessage(Message msg) {
95 AltosDroid ad = mAltosDroid.get();
97 case MSG_STATE_CHANGE:
98 if(D) Log.i(TAG, "MSG_STATE_CHANGE: " + 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("");
105 case TelemetryService.STATE_CONNECTING:
106 ad.mTitle.setText(R.string.title_connecting);
108 case TelemetryService.STATE_READY:
109 case TelemetryService.STATE_NONE:
110 ad.mTitle.setText(R.string.title_not_connected);
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);
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();
128 ad.getApplicationContext(),
129 msg.getData().getString(KEY_TOAST),
130 Toast.LENGTH_SHORT).show();
137 private ServiceConnection mConnection = new ServiceConnection() {
138 public void onServiceConnected(ComponentName className, IBinder service) {
139 mService = new Messenger(service);
141 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
142 msg.replyTo = mMessenger;
144 } catch (RemoteException e) {
145 // In this case the service has crashed before we could even do anything with it
149 public void onServiceDisconnected(ComponentName className) {
150 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
157 public void onCreate(Bundle savedInstanceState) {
158 super.onCreate(savedInstanceState);
159 if(D) Log.e(TAG, "+++ ON CREATE +++");
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);
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);
171 mSerialView = (TextView) findViewById(R.id.in);
172 mSerialView.setMovementMethod(new ScrollingMovementMethod());
173 mSerialView.setClickable(false);
174 mSerialView.setLongClickable(false);
176 // Get local Bluetooth adapter
177 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
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();
186 // Start Telemetry Service
187 startService(new Intent(AltosDroid.this, TelemetryService.class));
193 public void onStart() {
195 if(D) Log.e(TAG, "++ ON START ++");
197 if (!mBluetoothAdapter.isEnabled()) {
198 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
199 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
201 //if (mChatService == null) setupChat();
206 public synchronized void onResume() {
208 if(D) Log.e(TAG, "+ ON RESUME +");
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();
223 public synchronized void onPause() {
225 if(D) Log.e(TAG, "- ON PAUSE -");
229 public void onStop() {
231 if(D) Log.e(TAG, "-- ON STOP --");
235 public void onDestroy() {
240 if(D) Log.e(TAG, "--- ON DESTROY ---");
246 private void setupChat() {
247 Log.d(TAG, "setupChat()");
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);
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);
264 // Initialize the BluetoothChatService to perform bluetooth connections
265 mChatService = new BluetoothChatService(this, mHandler);
267 // Initialize the buffer for outgoing messages
268 mOutStringBuffer = new StringBuffer("");
274 * @param message A string of text to send.
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();
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);
290 // Reset out string buffer to zero and clear the edit text field
291 mOutStringBuffer.setLength(0);
292 mOutEditText.setText(mOutStringBuffer);
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);
306 if(D) Log.i(TAG, "END onEditorAction");
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) {
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
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();
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
343 //Message msg = Message.obtain(null, TelemetryService.MSG_CONNECT_TELEBT);
345 //mService.send(msg);
346 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
347 } catch (RemoteException e) {
354 public boolean onCreateOptionsMenu(Menu menu) {
355 MenuInflater inflater = getMenuInflater();
356 inflater.inflate(R.menu.option_menu, menu);
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);
374 void doBindService() {
375 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
379 void doUnbindService() {
381 // If we have received the service, and hence registered with it, then now is the time to unregister.
382 if (mService != null) {
384 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
385 msg.replyTo = mMessenger;
387 } catch (RemoteException e) {
388 // There is nothing special we need to do if the service has crashed.
391 // Detach our existing connection.
392 unbindService(mConnection);