54b61c67ca793849d19e0c3707e49977d7165d93
[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 android.app.Activity;
21 import android.bluetooth.BluetoothAdapter;
22 import android.bluetooth.BluetoothDevice;
23 import android.content.Intent;
24 import android.content.Context;
25 import android.content.ComponentName;
26 import android.content.ServiceConnection;
27 import android.os.IBinder;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.os.Message;
31 import android.os.Messenger;
32 import android.os.RemoteException;
33 import android.text.method.ScrollingMovementMethod;
34 import android.util.Log;
35 //import android.view.KeyEvent;
36 import android.view.Menu;
37 import android.view.MenuInflater;
38 import android.view.MenuItem;
39 //import android.view.View;
40 import android.view.Window;
41 //import android.view.View.OnClickListener;
42 //import android.view.inputmethod.EditorInfo;
43 //import android.widget.Button;
44 //import android.widget.EditText;
45 import android.widget.TextView;
46 import android.widget.Toast;
47 import org.altusmetrum.AltosDroid.R;
48
49 /**
50  * This is the main Activity that displays the current chat session.
51  */
52 public class AltosDroid extends Activity {
53         // Debugging
54         private static final String TAG = "AltosDroid";
55         private static final boolean D = true;
56
57     // Message types sent from the BluetoothChatService Handler
58     public static final int MESSAGE_STATE_CHANGE = 1;
59     public static final int MESSAGE_READ = 2;
60     public static final int MESSAGE_WRITE = 3;
61     public static final int MESSAGE_DEVICE_NAME = 4;
62     public static final int MESSAGE_TOAST = 5;
63
64     // Key names received from the BluetoothChatService Handler
65     public static final String DEVICE_NAME = "device_name";
66     public static final String TOAST = "toast";
67
68
69
70         // Intent request codes
71         private static final int REQUEST_CONNECT_DEVICE = 1;
72         private static final int REQUEST_ENABLE_BT      = 2;
73
74         // Layout Views
75         private TextView mTitle;
76         private TextView mSerialView;
77         //private EditText mOutEditText;
78         //private Button mSendButton;
79
80         private boolean mIsBound;
81         Messenger mService = null;
82
83         // Name of the connected device
84         private String mConnectedDeviceName = null;
85         // Local Bluetooth adapter
86         private BluetoothAdapter mBluetoothAdapter = null;
87
88         };
89
90
91         private ServiceConnection mConnection = new ServiceConnection() {
92                 public void onServiceConnected(ComponentName className, IBinder service) {
93                         mService = new Messenger(service);
94                 }
95
96                 public void onServiceDisconnected(ComponentName className) {
97                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
98                         mService = null;
99                 }
100         };
101
102
103         @Override
104         public void onCreate(Bundle savedInstanceState) {
105                 super.onCreate(savedInstanceState);
106                 if(D) Log.e(TAG, "+++ ON CREATE +++");
107
108                 // Set up the window layout
109                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
110                 setContentView(R.layout.main);
111                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
112
113                 // Set up the custom title
114                 mTitle = (TextView) findViewById(R.id.title_left_text);
115                 mTitle.setText(R.string.app_name);
116                 mTitle = (TextView) findViewById(R.id.title_right_text);
117
118                 mSerialView = (TextView) findViewById(R.id.in);
119                 mSerialView.setMovementMethod(new ScrollingMovementMethod());
120                 mSerialView.setClickable(false);
121                 mSerialView.setLongClickable(false);
122
123                 // Get local Bluetooth adapter
124                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
125
126                 // If the adapter is null, then Bluetooth is not supported
127                 if (mBluetoothAdapter == null) {
128                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
129                         finish();
130                         return;
131                 }
132
133                 // Start Telemetry Service
134                 startService(new Intent(AltosDroid.this, TelemetryService.class));
135
136                 doBindService();
137         }
138
139         @Override
140         public void onStart() {
141                 super.onStart();
142                 if(D) Log.e(TAG, "++ ON START ++");
143
144                 if (!mBluetoothAdapter.isEnabled()) {
145                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
146                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
147                 } else {
148                         //if (mChatService == null) setupChat();
149                 }
150         }
151
152         @Override
153         public synchronized void onResume() {
154                 super.onResume();
155                 if(D) Log.e(TAG, "+ ON RESUME +");
156
157                 // Performing this check in onResume() covers the case in which BT was
158                 // not enabled during onStart(), so we were paused to enable it...
159                 // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
160                 //if (mChatService != null) {
161                         // Only if the state is STATE_NONE, do we know that we haven't started already
162                         //if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
163                         // Start the Bluetooth chat services
164                         //mChatService.start();
165                         //}
166                 //}
167         }
168
169         @Override
170         public synchronized void onPause() {
171                 super.onPause();
172                 if(D) Log.e(TAG, "- ON PAUSE -");
173         }
174
175         @Override
176         public void onStop() {
177                 super.onStop();
178                 if(D) Log.e(TAG, "-- ON STOP --");
179         }
180
181         @Override
182         public void onDestroy() {
183                 super.onDestroy();
184
185                 doUnbindService();
186
187                 if(D) Log.e(TAG, "--- ON DESTROY ---");
188         }
189
190
191
192 /*
193         private void setupChat() {
194                 Log.d(TAG, "setupChat()");
195
196                 // Initialize the compose field with a listener for the return key
197                 mOutEditText = (EditText) findViewById(R.id.edit_text_out);
198                 mOutEditText.setOnEditorActionListener(mWriteListener);
199
200                 // Initialize the send button with a listener that for click events
201                 mSendButton = (Button) findViewById(R.id.button_send);
202                 mSendButton.setOnClickListener(new OnClickListener() {
203                         public void onClick(View v) {
204                                 // Send a message using content of the edit text widget
205                                 TextView view = (TextView) findViewById(R.id.edit_text_out);
206                                 String message = view.getText().toString();
207                                 sendMessage(message);
208                         }
209                 });
210
211                 // Initialize the BluetoothChatService to perform bluetooth connections
212                 mChatService = new BluetoothChatService(this, mHandler);
213
214                 // Initialize the buffer for outgoing messages
215                 mOutStringBuffer = new StringBuffer("");
216         }
217 */
218
219         /**
220          * Sends a message.
221          * @param message  A string of text to send.
222          */
223         /*
224         private void sendMessage(String message) {
225                 // Check that we're actually connected before trying anything
226                 if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
227                         Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
228                         return;
229                 }
230
231                 // Check that there's actually something to send
232                 if (message.length() > 0) {
233                         // Get the message bytes and tell the BluetoothChatService to write
234                         byte[] send = message.getBytes();
235                         mChatService.write(send);
236
237                         // Reset out string buffer to zero and clear the edit text field
238                         mOutStringBuffer.setLength(0);
239                         mOutEditText.setText(mOutStringBuffer);
240                 }
241         }
242
243
244         // The action listener for the EditText widget, to listen for the return key
245         private TextView.OnEditorActionListener mWriteListener =
246                 new TextView.OnEditorActionListener() {
247                 public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
248                         // If the action is a key-up event on the return key, send the message
249                         if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
250                                 String message = view.getText().toString();
251                                 sendMessage(message);
252                         }
253                         if(D) Log.i(TAG, "END onEditorAction");
254                         return true;
255                 }
256         };
257         */
258
259         public void onActivityResult(int requestCode, int resultCode, Intent data) {
260                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
261                 switch (requestCode) {
262                 case REQUEST_CONNECT_DEVICE:
263                         // When DeviceListActivity returns with a device to connect to
264                         if (resultCode == Activity.RESULT_OK) {
265                                 connectDevice(data);
266                         }
267                         break;
268                 case REQUEST_ENABLE_BT:
269                         // When the request to enable Bluetooth returns
270                         if (resultCode == Activity.RESULT_OK) {
271                                 // Bluetooth is now enabled, so set up a chat session
272                                 //setupChat();
273                         } else {
274                                 // User did not enable Bluetooth or an error occured
275                                 Log.d(TAG, "BT not enabled");
276                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
277                                 Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
278                                 finish();
279                         }
280                 }
281         }
282
283         private void connectDevice(Intent data) {
284                 // Get the device MAC address
285                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
286                 // Get the BLuetoothDevice object
287                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
288                 // Attempt to connect to the device
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
313         void doBindService() {
314                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
315                 mIsBound = true;
316         }
317
318         void doUnbindService() {
319                 if (mIsBound) {
320                         // If we have received the service, and hence registered with it, then now is the time to unregister.
321                         // Detach our existing connection.
322                         unbindService(mConnection);
323                         mIsBound = false;
324                 }
325         }
326
327 }