Convert to AndroidX from support_v4
[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                 super.onCreate(savedInstanceState);
59
60                 // Setup the window
61                 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
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                 setProgressBarIndeterminateVisibility(true);
139                 setTitle(R.string.scanning);
140
141                 // Turn on sub-title for new devices
142                 findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
143
144                 // If we're already discovering, stop it
145                 if (mBtAdapter.isDiscovering()) {
146                         mBtAdapter.cancelDiscovery();
147                 }
148
149                 // Request discover from BluetoothAdapter
150                 mBtAdapter.startDiscovery();
151         }
152
153         // The on-click listener for all devices in the ListViews
154         private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
155                 public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
156                         // Cancel discovery because it's costly and we're about to connect
157                         mBtAdapter.cancelDiscovery();
158
159                         // Get the device MAC address, which is the last 17 chars in the View
160                         String info = ((TextView) v).getText().toString();
161                         String address = info.substring(info.length() - 17);
162
163                         int newline = info.indexOf('\n');
164
165                         String name = null;
166                         if (newline > 0)
167                                 name = info.substring(0, newline);
168                         else
169                                 name = info;
170
171                         AltosDebug.debug("******* selected item '%s'", info);
172
173                         // Create the result Intent and include the MAC address
174                         Intent intent = new Intent();
175                         intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
176                         intent.putExtra(EXTRA_DEVICE_NAME, name);
177
178                         // Set result and finish this Activity
179                         setResult(Activity.RESULT_OK, intent);
180                         finish();
181                 }
182         };
183
184         // The BroadcastReceiver that listens for discovered devices and
185         // changes the title when discovery is finished
186         private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
187                 @Override
188                 public void onReceive(Context context, Intent intent) {
189                         String action = intent.getAction();
190
191                         // When discovery finds a device
192                         if (BluetoothDevice.ACTION_FOUND.equals(action)) {
193
194                                 /* Get the BluetoothDevice object from the Intent
195                                  */
196                                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
197
198                                 /* If it's already paired, skip it, because it's been listed already
199                                  */
200                                 if (device != null && device.getBondState() != BluetoothDevice.BOND_BONDED)
201                                 {
202                                         String  name = device.getName();
203                                         if (name != null && name.startsWith("TeleBT"))
204                                                 mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
205                                 }
206
207                         /* When discovery is finished, change the Activity title
208                          */
209                         } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
210                                 setProgressBarIndeterminateVisibility(false);
211                                 setTitle(R.string.select_device);
212                                 if (mNewDevicesArrayAdapter.getCount() == 0) {
213                                         String noDevices = getResources().getText(R.string.none_found).toString();
214                                         mNewDevicesArrayAdapter.add(noDevices);
215                                 }
216                         }
217                 }
218         };
219
220 }