4af117a29bbde343c91a0a0b8c6416aa0836280d
[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.view.View;
31 import android.view.Window;
32 import android.view.View.OnClickListener;
33 import android.widget.AdapterView;
34 import android.widget.ArrayAdapter;
35 import android.widget.Button;
36 import android.widget.ListView;
37 import android.widget.TextView;
38 import android.widget.AdapterView.OnItemClickListener;
39
40 /**
41  * This Activity appears as a dialog. It lists any paired devices and
42  * devices detected in the area after discovery. When a device is chosen
43  * by the user, the MAC address of the device is sent back to the parent
44  * Activity in the result Intent.
45  */
46 public class DeviceListActivity extends Activity {
47
48         // Return Intent extra
49         public static final String EXTRA_DEVICE_ADDRESS = "device_address";
50         public static final String EXTRA_DEVICE_NAME = "device_name";
51
52         // Member fields
53         private BluetoothAdapter mBtAdapter;
54         private ArrayAdapter<String> mPairedDevicesArrayAdapter;
55         private ArrayAdapter<String> mNewDevicesArrayAdapter;
56
57         @Override
58         protected void onCreate(Bundle savedInstanceState) {
59                 super.onCreate(savedInstanceState);
60
61                 // Setup the window
62                 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
63                 setContentView(R.layout.device_list);
64
65                 // Set result CANCELED incase the user backs out
66                 setResult(Activity.RESULT_CANCELED);
67
68                 // Initialize the button to perform device discovery
69                 Button scanButton = (Button) findViewById(R.id.button_scan);
70                 scanButton.setOnClickListener(new OnClickListener() {
71                         public void onClick(View v) {
72                                 doDiscovery();
73                                 v.setVisibility(View.GONE);
74                         }
75                 });
76
77                 // Initialize array adapters. One for already paired devices and
78                 // one for newly discovered devices
79                 mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
80                 mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
81
82                 // Find and set up the ListView for paired devices
83                 ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
84                 pairedListView.setAdapter(mPairedDevicesArrayAdapter);
85                 pairedListView.setOnItemClickListener(mDeviceClickListener);
86
87                 // Find and set up the ListView for newly discovered devices
88                 ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
89                 newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
90                 newDevicesListView.setOnItemClickListener(mDeviceClickListener);
91
92                 // Register for broadcasts when a device is discovered
93                 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
94                 this.registerReceiver(mReceiver, filter);
95
96                 // Register for broadcasts when discovery has finished
97                 filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
98                 this.registerReceiver(mReceiver, filter);
99
100                 // Get the local Bluetooth adapter
101                 mBtAdapter = BluetoothAdapter.getDefaultAdapter();
102
103                 // Get a set of currently paired devices
104                 Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
105
106                 // If there are paired devices, add each one to the ArrayAdapter
107                 if (pairedDevices.size() > 0) {
108                         findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
109                         for (BluetoothDevice device : pairedDevices)
110                                 if (device.getName().startsWith("TeleBT"))
111                                         mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
112
113                 } else {
114                         String noDevices = getResources().getText(R.string.none_paired).toString();
115                         mPairedDevicesArrayAdapter.add(noDevices);
116                 }
117         }
118
119         @Override
120         protected void onDestroy() {
121                 super.onDestroy();
122
123                 // Make sure we're not doing discovery anymore
124                 if (mBtAdapter != null) {
125                         mBtAdapter.cancelDiscovery();
126                 }
127
128                 // Unregister broadcast listeners
129                 this.unregisterReceiver(mReceiver);
130         }
131
132         /**
133         * Start device discover with the BluetoothAdapter
134         */
135         private void doDiscovery() {
136                 AltosDebug.debug("doDiscovery()");
137
138                 // Indicate scanning in the title
139                 setProgressBarIndeterminateVisibility(true);
140                 setTitle(R.string.scanning);
141
142                 // Turn on sub-title for new devices
143                 findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
144
145                 // If we're already discovering, stop it
146                 if (mBtAdapter.isDiscovering()) {
147                         mBtAdapter.cancelDiscovery();
148                 }
149
150                 // Request discover from BluetoothAdapter
151                 mBtAdapter.startDiscovery();
152         }
153
154         // The on-click listener for all devices in the ListViews
155         private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
156                 public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
157                         // Cancel discovery because it's costly and we're about to connect
158                         mBtAdapter.cancelDiscovery();
159
160                         // Get the device MAC address, which is the last 17 chars in the View
161                         String info = ((TextView) v).getText().toString();
162                         String address = info.substring(info.length() - 17);
163
164                         int newline = info.indexOf('\n');
165
166                         String name = null;
167                         if (newline > 0)
168                                 name = info.substring(0, newline);
169                         else
170                                 name = info;
171
172                         AltosDebug.debug("******* selected item '%s'", info);
173
174                         // Create the result Intent and include the MAC address
175                         Intent intent = new Intent();
176                         intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
177                         intent.putExtra(EXTRA_DEVICE_NAME, name);
178
179                         // Set result and finish this Activity
180                         setResult(Activity.RESULT_OK, intent);
181                         finish();
182                 }
183         };
184
185         // The BroadcastReceiver that listens for discovered devices and
186         // changes the title when discovery is finished
187         private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
188                 @Override
189                 public void onReceive(Context context, Intent intent) {
190                         String action = intent.getAction();
191
192                         // When discovery finds a device
193                         if (BluetoothDevice.ACTION_FOUND.equals(action)) {
194                                 // Get the BluetoothDevice object from the Intent
195                                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
196                                 // If it's already paired, skip it, because it's been listed already
197                                 if (   device.getBondState() != BluetoothDevice.BOND_BONDED
198                                     && device.getName().startsWith("TeleBT")               ) {
199                                         mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
200                                 }
201                         // When discovery is finished, change the Activity title
202                         } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
203                                 setProgressBarIndeterminateVisibility(false);
204                                 setTitle(R.string.select_device);
205                                 if (mNewDevicesArrayAdapter.getCount() == 0) {
206                                         String noDevices = getResources().getText(R.string.none_found).toString();
207                                         mNewDevicesArrayAdapter.add(noDevices);
208                                 }
209                         }
210                 }
211         };
212
213 }