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