altosdroid: Deal with bluetooth connection failures better
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / DeviceListActivity.java
1 /*
2  * Copyright (C) 2009 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.altusmetrum.AltosDroid;
18
19 import java.util.Set;
20 import org.altusmetrum.AltosDroid.R;
21
22 import android.app.Activity;
23 import android.bluetooth.BluetoothAdapter;
24 import android.bluetooth.BluetoothDevice;
25 import android.content.BroadcastReceiver;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.IntentFilter;
29 import android.os.Bundle;
30 import android.util.Log;
31 import android.view.View;
32 import android.view.Window;
33 import android.view.View.OnClickListener;
34 import android.widget.AdapterView;
35 import android.widget.ArrayAdapter;
36 import android.widget.Button;
37 import android.widget.ListView;
38 import android.widget.TextView;
39 import android.widget.AdapterView.OnItemClickListener;
40
41 /**
42  * This Activity appears as a dialog. It lists any paired devices and
43  * devices detected in the area after discovery. When a device is chosen
44  * by the user, the MAC address of the device is sent back to the parent
45  * Activity in the result Intent.
46  */
47 public class DeviceListActivity extends Activity {
48         // Debugging
49         private static final String TAG = "DeviceListActivity";
50         private static final boolean D = true;
51
52         // Return Intent extra
53         public static final String EXTRA_DEVICE_ADDRESS = "device_address";
54         public static final String EXTRA_DEVICE_NAME = "device_name";
55
56         // Member fields
57         private BluetoothAdapter mBtAdapter;
58         private ArrayAdapter<String> mPairedDevicesArrayAdapter;
59         private ArrayAdapter<String> mNewDevicesArrayAdapter;
60
61         @Override
62         protected void onCreate(Bundle savedInstanceState) {
63                 super.onCreate(savedInstanceState);
64
65                 // Setup the window
66                 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
67                 setContentView(R.layout.device_list);
68
69                 // Set result CANCELED incase the user backs out
70                 setResult(Activity.RESULT_CANCELED);
71
72                 // Initialize the button to perform device discovery
73                 Button scanButton = (Button) findViewById(R.id.button_scan);
74                 scanButton.setOnClickListener(new OnClickListener() {
75                         public void onClick(View v) {
76                                 doDiscovery();
77                                 v.setVisibility(View.GONE);
78                         }
79                 });
80
81                 // Initialize array adapters. One for already paired devices and
82                 // one for newly discovered devices
83                 mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
84                 mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
85
86                 // Find and set up the ListView for paired devices
87                 ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
88                 pairedListView.setAdapter(mPairedDevicesArrayAdapter);
89                 pairedListView.setOnItemClickListener(mDeviceClickListener);
90
91                 // Find and set up the ListView for newly discovered devices
92                 ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
93                 newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
94                 newDevicesListView.setOnItemClickListener(mDeviceClickListener);
95
96                 // Register for broadcasts when a device is discovered
97                 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
98                 this.registerReceiver(mReceiver, filter);
99
100                 // Register for broadcasts when discovery has finished
101                 filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
102                 this.registerReceiver(mReceiver, filter);
103
104                 // Get the local Bluetooth adapter
105                 mBtAdapter = BluetoothAdapter.getDefaultAdapter();
106
107                 // Get a set of currently paired devices
108                 Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
109
110                 // If there are paired devices, add each one to the ArrayAdapter
111                 if (pairedDevices.size() > 0) {
112                         findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
113                         for (BluetoothDevice device : pairedDevices)
114                                 if (device.getName().startsWith("TeleBT"))
115                                         mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
116
117                 } else {
118                         String noDevices = getResources().getText(R.string.none_paired).toString();
119                         mPairedDevicesArrayAdapter.add(noDevices);
120                 }
121         }
122
123         @Override
124         protected void onDestroy() {
125                 super.onDestroy();
126
127                 // Make sure we're not doing discovery anymore
128                 if (mBtAdapter != null) {
129                         mBtAdapter.cancelDiscovery();
130                 }
131
132                 // Unregister broadcast listeners
133                 this.unregisterReceiver(mReceiver);
134         }
135
136         /**
137         * Start device discover with the BluetoothAdapter
138         */
139         private void doDiscovery() {
140                 if (D) Log.d(TAG, "doDiscovery()");
141
142                 // Indicate scanning in the title
143                 setProgressBarIndeterminateVisibility(true);
144                 setTitle(R.string.scanning);
145
146                 // Turn on sub-title for new devices
147                 findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
148
149                 // If we're already discovering, stop it
150                 if (mBtAdapter.isDiscovering()) {
151                         mBtAdapter.cancelDiscovery();
152                 }
153
154                 // Request discover from BluetoothAdapter
155                 mBtAdapter.startDiscovery();
156         }
157
158         // The on-click listener for all devices in the ListViews
159         private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
160                 public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
161                         // Cancel discovery because it's costly and we're about to connect
162                         mBtAdapter.cancelDiscovery();
163
164                         // Get the device MAC address, which is the last 17 chars in the View
165                         String info = ((TextView) v).getText().toString();
166                         String address = info.substring(info.length() - 17);
167
168                         int newline = info.indexOf('\n');
169
170                         String name = null;
171                         if (newline > 0)
172                                 name = info.substring(0, newline);
173                         else
174                                 name = info;
175
176                         if (D) Log.d(TAG, String.format("******* selected item '%s'", info));
177
178                         // Create the result Intent and include the MAC address
179                         Intent intent = new Intent();
180                         intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
181                         intent.putExtra(EXTRA_DEVICE_NAME, name);
182
183                         // Set result and finish this Activity
184                         setResult(Activity.RESULT_OK, intent);
185                         finish();
186                 }
187         };
188
189         // The BroadcastReceiver that listens for discovered devices and
190         // changes the title when discovery is finished
191         private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
192                 @Override
193                 public void onReceive(Context context, Intent intent) {
194                         String action = intent.getAction();
195
196                         // When discovery finds a device
197                         if (BluetoothDevice.ACTION_FOUND.equals(action)) {
198                                 // Get the BluetoothDevice object from the Intent
199                                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
200                                 // If it's already paired, skip it, because it's been listed already
201                                 if (   device.getBondState() != BluetoothDevice.BOND_BONDED
202                                     && device.getName().startsWith("TeleBT")               ) {
203                                         mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
204                                 }
205                         // When discovery is finished, change the Activity title
206                         } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
207                                 setProgressBarIndeterminateVisibility(false);
208                                 setTitle(R.string.select_device);
209                                 if (mNewDevicesArrayAdapter.getCount() == 0) {
210                                         String noDevices = getResources().getText(R.string.none_found).toString();
211                                         mNewDevicesArrayAdapter.add(noDevices);
212                                 }
213                         }
214                 }
215         };
216
217 }