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 android.app.Activity;
21 import android.bluetooth.BluetoothAdapter;
22 import android.bluetooth.BluetoothDevice;
23 import android.content.Intent;
24 import android.os.Bundle;
25 import android.os.Handler;
26 import android.os.Message;
27 import android.text.method.ScrollingMovementMethod;
28 import android.util.Log;
29 import android.view.KeyEvent;
30 import android.view.Menu;
31 import android.view.MenuInflater;
32 import android.view.MenuItem;
33 import android.view.View;
34 import android.view.Window;
35 import android.view.View.OnClickListener;
36 import android.view.inputmethod.EditorInfo;
37 import android.widget.Button;
38 import android.widget.EditText;
39 import android.widget.TextView;
40 import android.widget.Toast;
41 import org.altusmetrum.AltosDroid.R;
42 import org.altusmetrum.AltosLib.*;
45 * This is the main Activity that displays the current chat session.
47 public class AltosDroid extends Activity {
49 private static final String TAG = "AltosDroid";
50 private static final boolean D = true;
52 // Message types sent from the BluetoothChatService Handler
53 public static final int MESSAGE_STATE_CHANGE = 1;
54 public static final int MESSAGE_READ = 2;
55 public static final int MESSAGE_WRITE = 3;
56 public static final int MESSAGE_DEVICE_NAME = 4;
57 public static final int MESSAGE_TOAST = 5;
59 // Key names received from the BluetoothChatService Handler
60 public static final String DEVICE_NAME = "device_name";
61 public static final String TOAST = "toast";
64 private EditText mOutEditText;
65 private Button mSendButton;
67 // String buffer for outgoing messages
68 private StringBuffer mOutStringBuffer;
69 // Member object for the chat services
70 private BluetoothChatService mChatService = null;
71 // Intent request codes
72 private static final int REQUEST_CONNECT_DEVICE = 1;
73 private static final int REQUEST_ENABLE_BT = 2;
76 private TextView mTitle;
77 private TextView mSerialView;
78 // Name of the connected device
79 private String mConnectedDeviceName = null;
80 // Local Bluetooth adapter
81 private BluetoothAdapter mBluetoothAdapter = null;
84 public void onCreate(Bundle savedInstanceState) {
85 super.onCreate(savedInstanceState);
86 if(D) Log.e(TAG, "+++ ON CREATE +++");
88 // Set up the window layout
89 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
90 setContentView(R.layout.main);
91 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
93 // Get local Bluetooth adapter
94 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
95 // Set up the custom title
96 mTitle = (TextView) findViewById(R.id.title_left_text);
97 mTitle.setText(R.string.app_name);
98 mTitle = (TextView) findViewById(R.id.title_right_text);
100 // If the adapter is null, then Bluetooth is not supported
101 if (mBluetoothAdapter == null) {
102 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
110 public void onStart() {
112 if(D) Log.e(TAG, "++ ON START ++");
114 if (!mBluetoothAdapter.isEnabled()) {
115 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
116 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
118 if (mChatService == null) setupChat();
123 public synchronized void onResume() {
125 if(D) Log.e(TAG, "+ ON RESUME +");
127 // Performing this check in onResume() covers the case in which BT was
128 // not enabled during onStart(), so we were paused to enable it...
129 // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
130 if (mChatService != null) {
131 // Only if the state is STATE_NONE, do we know that we haven't started already
132 if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
133 // Start the Bluetooth chat services
134 mChatService.start();
140 public synchronized void onPause() {
142 if(D) Log.e(TAG, "- ON PAUSE -");
146 public void onStop() {
148 if(D) Log.e(TAG, "-- ON STOP --");
152 public void onDestroy() {
154 // Stop the Bluetooth chat services
155 if (mChatService != null) mChatService.stop();
156 if(D) Log.e(TAG, "--- ON DESTROY ---");
161 private void setupChat() {
162 Log.d(TAG, "setupChat()");
164 mSerialView = (TextView) findViewById(R.id.in);
165 mSerialView.setMovementMethod(new ScrollingMovementMethod());
166 mSerialView.setClickable(false);
167 mSerialView.setLongClickable(false);
169 // Initialize the compose field with a listener for the return key
170 mOutEditText = (EditText) findViewById(R.id.edit_text_out);
171 mOutEditText.setOnEditorActionListener(mWriteListener);
173 // Initialize the send button with a listener that for click events
174 mSendButton = (Button) findViewById(R.id.button_send);
175 mSendButton.setOnClickListener(new OnClickListener() {
176 public void onClick(View v) {
177 // Send a message using content of the edit text widget
178 TextView view = (TextView) findViewById(R.id.edit_text_out);
179 String message = view.getText().toString();
180 sendMessage(message);
184 // Initialize the BluetoothChatService to perform bluetooth connections
185 mChatService = new BluetoothChatService(this, mHandler);
187 // Initialize the buffer for outgoing messages
188 mOutStringBuffer = new StringBuffer("");
193 * @param message A string of text to send.
196 private void sendMessage(String message) {
197 // Check that we're actually connected before trying anything
198 if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
199 Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
203 // Check that there's actually something to send
204 if (message.length() > 0) {
205 // Get the message bytes and tell the BluetoothChatService to write
206 byte[] send = message.getBytes();
207 mChatService.write(send);
209 // Reset out string buffer to zero and clear the edit text field
210 mOutStringBuffer.setLength(0);
211 mOutEditText.setText(mOutStringBuffer);
216 // The action listener for the EditText widget, to listen for the return key
217 private TextView.OnEditorActionListener mWriteListener =
218 new TextView.OnEditorActionListener() {
219 public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
220 // If the action is a key-up event on the return key, send the message
221 if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
222 String message = view.getText().toString();
223 sendMessage(message);
225 if(D) Log.i(TAG, "END onEditorAction");
231 // The Handler that gets information back from the BluetoothChatService
232 private final Handler mHandler = new Handler() {
234 public void handleMessage(Message msg) {
236 case MESSAGE_STATE_CHANGE:
237 if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
239 case BluetoothChatService.STATE_CONNECTED:
240 mTitle.setText(R.string.title_connected_to);
241 mTitle.append(mConnectedDeviceName);
242 mSerialView.setText("");
244 case BluetoothChatService.STATE_CONNECTING:
245 mTitle.setText(R.string.title_connecting);
247 case BluetoothChatService.STATE_READY:
248 case BluetoothChatService.STATE_NONE:
249 mTitle.setText(R.string.title_not_connected);
254 byte[] writeBuf = (byte[]) msg.obj;
255 // construct a string from the buffer
256 String writeMessage = new String(writeBuf);
257 mSerialView.append(writeMessage + '\n');
260 byte[] readBuf = (byte[]) msg.obj;
261 // construct a string from the valid bytes in the buffer
262 String readMessage = new String(readBuf, 0, msg.arg1);
263 mSerialView.append(readMessage);
265 case MESSAGE_DEVICE_NAME:
266 // save the connected device's name
267 mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
268 Toast.makeText(getApplicationContext(), "Connected to "
269 + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
272 Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
273 Toast.LENGTH_SHORT).show();
279 public void onActivityResult(int requestCode, int resultCode, Intent data) {
280 if(D) Log.d(TAG, "onActivityResult " + resultCode);
281 switch (requestCode) {
282 case REQUEST_CONNECT_DEVICE:
283 // When DeviceListActivity returns with a device to connect to
284 if (resultCode == Activity.RESULT_OK) {
288 case REQUEST_ENABLE_BT:
289 // When the request to enable Bluetooth returns
290 if (resultCode == Activity.RESULT_OK) {
291 // Bluetooth is now enabled, so set up a chat session
294 // User did not enable Bluetooth or an error occured
295 Log.d(TAG, "BT not enabled");
296 stopService(new Intent(AltosDroid.this, TelemetryService.class));
297 Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
303 private void connectDevice(Intent data) {
304 // Get the device MAC address
305 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
306 // Get the BLuetoothDevice object
307 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
308 // Attempt to connect to the device
309 mChatService.connect(device);
314 public boolean onCreateOptionsMenu(Menu menu) {
315 MenuInflater inflater = getMenuInflater();
316 inflater.inflate(R.menu.option_menu, menu);
321 public boolean onOptionsItemSelected(MenuItem item) {
322 Intent serverIntent = null;
323 switch (item.getItemId()) {
324 case R.id.telemetry_service_control:
325 serverIntent = new Intent(this, TelemetryServiceActivities.Controller.class);
326 startActivity(serverIntent);
328 case R.id.telemetry_service_bind:
329 serverIntent = new Intent(this, TelemetryServiceActivities.Binding.class);
330 startActivity(serverIntent);
332 case R.id.connect_scan:
333 // Launch the DeviceListActivity to see devices and do scan
334 serverIntent = new Intent(this, DeviceListActivity.class);
335 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);