|
| 1 | +package com.meow.hanwei.epdandroidworkshop; |
| 2 | + |
| 3 | +import android.bluetooth.BluetoothAdapter; |
| 4 | +import android.bluetooth.BluetoothDevice; |
| 5 | +import android.bluetooth.BluetoothSocket; |
| 6 | +import android.content.BroadcastReceiver; |
| 7 | +import android.content.Context; |
| 8 | +import android.content.Intent; |
| 9 | +import android.content.IntentFilter; |
| 10 | +import android.os.Handler; |
| 11 | +import android.os.Message; |
| 12 | +import android.os.ParcelUuid; |
| 13 | +import android.support.v7.app.AppCompatActivity; |
| 14 | +import android.os.Bundle; |
| 15 | +import android.util.Log; |
| 16 | +import android.view.View; |
| 17 | +import android.widget.AdapterView; |
| 18 | +import android.widget.ArrayAdapter; |
| 19 | +import android.widget.ListView; |
| 20 | +import android.widget.Toast; |
| 21 | + |
| 22 | +import java.io.IOException; |
| 23 | +import java.io.InputStream; |
| 24 | +import java.io.OutputStream; |
| 25 | +import java.lang.reflect.Method; |
| 26 | +import java.util.ArrayList; |
| 27 | +import java.util.Set; |
| 28 | +import java.util.UUID; |
| 29 | + |
| 30 | +public class MainActivity extends AppCompatActivity { |
| 31 | + |
| 32 | + private static final String TAG = "MY_APP_DEBUG_TAG"; // just the Tag that error messages will |
| 33 | + // contain when written to from this app |
| 34 | + |
| 35 | + private Handler mHandler = new Handler(); // handler that gets info from Bluetooth service |
| 36 | + |
| 37 | + /** |
| 38 | + * Bluetooth adapter |
| 39 | + */ |
| 40 | + BluetoothAdapter mBluetoothAdapter; |
| 41 | + |
| 42 | + /** |
| 43 | + * Bluetooth devices |
| 44 | + */ |
| 45 | + Set<BluetoothDevice> pairedDevices; // Set of devices that are paired to phone |
| 46 | + // (i.e. are bonded) |
| 47 | + |
| 48 | + ArrayList<String> nameList = new ArrayList(); // namelist of paired/in-range devices for adapter |
| 49 | + |
| 50 | + ArrayAdapter adapter; // adapter for listview |
| 51 | + ListView list; // to display names of devices |
| 52 | + |
| 53 | + ArrayList<BluetoothDevice> devices = new ArrayList<>(); |
| 54 | + private ConnectedThread connectedThread; |
| 55 | + |
| 56 | + private final BroadcastReceiver mReceiver = new BroadcastReceiver() { |
| 57 | + @Override |
| 58 | + public void onReceive(Context context, Intent intent) { |
| 59 | + String action = intent.getAction(); |
| 60 | + if (BluetoothDevice.ACTION_FOUND.equals(action)) { |
| 61 | + // Discovery has found a device. Get the BluetoothDevice |
| 62 | + // object and its info from the Intent. |
| 63 | + BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); |
| 64 | + String deviceName = device.getName(); |
| 65 | + if (!nameList.contains(deviceName)) { |
| 66 | + devices.add(device); |
| 67 | + nameList.add(deviceName); |
| 68 | + adapter.notifyDataSetChanged(); |
| 69 | + } |
| 70 | +// String deviceHardwareAddress = device.getAddress(); // MAC address |
| 71 | + } |
| 72 | + } |
| 73 | + }; |
| 74 | + |
| 75 | + @Override |
| 76 | + protected void onDestroy() { |
| 77 | + super.onDestroy(); |
| 78 | + // Don't forget to unregister the ACTION_FOUND receiver. |
| 79 | + unregisterReceiver(mReceiver); |
| 80 | + } |
| 81 | + |
| 82 | + @Override |
| 83 | + protected void onCreate(Bundle savedInstanceState) { |
| 84 | + super.onCreate(savedInstanceState); |
| 85 | + setContentView(R.layout.activity_main); |
| 86 | + |
| 87 | + // Register for broadcasts when a device is discovered. |
| 88 | + IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); |
| 89 | + registerReceiver(mReceiver, filter); |
| 90 | + |
| 91 | + adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, nameList); |
| 92 | + list = (ListView) findViewById(R.id.devices); |
| 93 | + list.setAdapter(adapter); |
| 94 | + |
| 95 | + list.setOnItemClickListener(new AdapterView.OnItemClickListener() { |
| 96 | + @Override |
| 97 | + public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { |
| 98 | + if (mBluetoothAdapter.isEnabled()) { |
| 99 | + String devName = (String) list.getItemAtPosition(i); |
| 100 | + for (BluetoothDevice bt : |
| 101 | + devices) { |
| 102 | + if (bt.getName().equals(devName)) { |
| 103 | + connectedThread = new ConnectedThread(bt); |
| 104 | + String meow = "1"; |
| 105 | + connectedThread.write(meow.getBytes()); |
| 106 | + Toast.makeText(MainActivity.this, "MADE CONNECTION", Toast.LENGTH_LONG).show(); |
| 107 | + } |
| 108 | + } |
| 109 | + } else { |
| 110 | + Toast.makeText(MainActivity.this, "Bluetooth is not on", Toast.LENGTH_SHORT).show(); |
| 111 | + } |
| 112 | + } |
| 113 | + }); |
| 114 | + |
| 115 | + mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); |
| 116 | + |
| 117 | + try { |
| 118 | + Method getUuidsMethod = BluetoothAdapter.class.getDeclaredMethod("getUuids", null); |
| 119 | + |
| 120 | + ParcelUuid[] uuids = (ParcelUuid[]) getUuidsMethod.invoke(mBluetoothAdapter, null); |
| 121 | + for (ParcelUuid uuid : uuids) { |
| 122 | + Log.d(TAG, "UUID: " + uuid.getUuid().toString()); |
| 123 | + } |
| 124 | + } catch (Exception e) { |
| 125 | + e.printStackTrace(); |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + protected void toggleBT(View view) { |
| 130 | + if (mBluetoothAdapter != null) { |
| 131 | + if (!mBluetoothAdapter.isEnabled()) { |
| 132 | + Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); |
| 133 | + startActivityForResult(enableIntent, 0); |
| 134 | + Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show(); |
| 135 | + } else { |
| 136 | + mBluetoothAdapter.disable(); |
| 137 | + Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_LONG).show(); |
| 138 | + } |
| 139 | + } else { |
| 140 | + Toast.makeText(getApplicationContext(), "Bluetooth not supported", Toast.LENGTH_LONG).show(); |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + protected void getPaired(View view) { |
| 145 | + if (mBluetoothAdapter.isEnabled()) { |
| 146 | + pairedDevices = mBluetoothAdapter.getBondedDevices(); |
| 147 | + nameList.clear(); |
| 148 | + devices.clear(); |
| 149 | + for (BluetoothDevice bt : pairedDevices) { |
| 150 | + if (!nameList.contains(bt.getName())) { |
| 151 | + nameList.add(bt.getName()); |
| 152 | + adapter.notifyDataSetChanged(); |
| 153 | + devices.add(bt); |
| 154 | + System.out.println(bt.getName() + ": "); |
| 155 | + for (ParcelUuid meow : |
| 156 | + bt.getUuids()) { |
| 157 | + System.out.println(meow.getUuid()); |
| 158 | + } |
| 159 | + } |
| 160 | + } |
| 161 | + Toast.makeText(getApplicationContext(), "Showing Paired Devices", Toast.LENGTH_SHORT).show(); |
| 162 | + } else { |
| 163 | + Toast.makeText(MainActivity.this, "Bluetooth is not on", Toast.LENGTH_SHORT).show(); |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + protected void discover(View view) { |
| 168 | + if (mBluetoothAdapter.isDiscovering()) { |
| 169 | + boolean discovering = mBluetoothAdapter.cancelDiscovery(); |
| 170 | + if (discovering) { |
| 171 | + Toast.makeText(MainActivity.this, "Stopping discovery", Toast.LENGTH_LONG).show(); |
| 172 | + } else { |
| 173 | + Toast.makeText(MainActivity.this, "Could not start discovery", Toast.LENGTH_LONG).show(); |
| 174 | + } |
| 175 | + } else { |
| 176 | + mBluetoothAdapter.startDiscovery(); |
| 177 | + Toast.makeText(MainActivity.this, "Started discovering", Toast.LENGTH_LONG).show(); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + |
| 182 | + private interface MessageConstants { |
| 183 | + int MESSAGE_READ = 0; |
| 184 | + int MESSAGE_WRITE = 1; |
| 185 | + int MESSAGE_TOAST = 2; |
| 186 | + // ... (Add other message types here as needed.) |
| 187 | + } |
| 188 | + |
| 189 | + |
| 190 | + private class ConnectedThread extends Thread { |
| 191 | + private final BluetoothSocket mmSocket; |
| 192 | + private final BluetoothDevice mmDevice; |
| 193 | + private final InputStream mmInStream; |
| 194 | + private final OutputStream mmOutStream; |
| 195 | + private byte[] mmBuffer; // mmBuffer store for the stream |
| 196 | + |
| 197 | + protected ConnectedThread(BluetoothDevice device) { |
| 198 | + // Use a temporary object that is later assigned to mmSocket |
| 199 | + // because mmSocket is final. |
| 200 | + BluetoothSocket tmp = null; |
| 201 | + mmDevice = device; |
| 202 | + |
| 203 | + try { |
| 204 | + // Get a BluetoothSocket to connect with the given BluetoothDevice. |
| 205 | + // MY_UUID is the app's UUID string. |
| 206 | + |
| 207 | + // tmp = device.createRfcommSocketToServiceRecord(mmDevice.getUuids()[0].getUuid()); |
| 208 | + // This gets the first item from the array returned by getUuids(). |
| 209 | + |
| 210 | + // 00001101 represents the COM/Serial port for bluetooth. |
| 211 | + tmp = mmDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); |
| 212 | + tmp.connect(); |
| 213 | + } catch (IOException e) { |
| 214 | + Log.e(TAG, "Socket's create() method failed", e); |
| 215 | + } |
| 216 | + mmSocket = tmp; |
| 217 | + InputStream tmpIn = null; |
| 218 | + OutputStream tmpOut = null; |
| 219 | + |
| 220 | + // Get the input and output streams; using temp objects because |
| 221 | + // member streams are final. |
| 222 | + try { |
| 223 | + tmpIn = mmSocket.getInputStream(); |
| 224 | + } catch (IOException e) { |
| 225 | + Log.e(TAG, "Error occurred when creating input stream", e); |
| 226 | + } |
| 227 | + try { |
| 228 | + tmpOut = mmSocket.getOutputStream(); |
| 229 | + } catch (IOException e) { |
| 230 | + Log.e(TAG, "Error occurred when creating output stream", e); |
| 231 | + } |
| 232 | + |
| 233 | + mmInStream = tmpIn; |
| 234 | + mmOutStream = tmpOut; |
| 235 | + } |
| 236 | + |
| 237 | + public void run() { |
| 238 | + mmBuffer = new byte[1024]; |
| 239 | + int numBytes; // bytes returned from read() |
| 240 | + |
| 241 | + // Keep listening to the InputStream until an exception occurs. |
| 242 | + while (true) { |
| 243 | + try { |
| 244 | + // Read from the InputStream. |
| 245 | + numBytes = mmInStream.read(mmBuffer); |
| 246 | + // Send the obtained bytes to the UI activity. |
| 247 | + Message readMsg = mHandler.obtainMessage( |
| 248 | + MessageConstants.MESSAGE_READ, numBytes, -1, |
| 249 | + mmBuffer); |
| 250 | + readMsg.sendToTarget(); |
| 251 | + } catch (IOException e) { |
| 252 | + Log.d(TAG, "Input stream was disconnected", e); |
| 253 | + break; |
| 254 | + } |
| 255 | + } |
| 256 | + } |
| 257 | + |
| 258 | + // Call this from the main activity to send data to the remote device. |
| 259 | + protected void write(byte[] msgbytes) { |
| 260 | + try { |
| 261 | + mmOutStream.write(msgbytes); // This is the only call that's actually sending |
| 262 | + // data to the connected bluetooth device |
| 263 | + |
| 264 | + // Share the sent message with the UI activity. |
| 265 | + Message writtenMsg = mHandler.obtainMessage( |
| 266 | + MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer); |
| 267 | + writtenMsg.sendToTarget(); |
| 268 | + } catch (IOException e) { |
| 269 | + Log.e(TAG, "Error occurred when sending data", e); |
| 270 | + |
| 271 | + // Send a failure message back to the activity. |
| 272 | + Message writeErrorMsg = |
| 273 | + mHandler.obtainMessage(MessageConstants.MESSAGE_TOAST); |
| 274 | + Bundle bundle = new Bundle(); |
| 275 | + bundle.putString("toast", |
| 276 | + "Couldn't send data to the other device"); |
| 277 | + writeErrorMsg.setData(bundle); |
| 278 | + mHandler.sendMessage(writeErrorMsg); |
| 279 | + } |
| 280 | + } |
| 281 | + |
| 282 | + // Call this method from the main activity to shut down the connection. |
| 283 | + protected void cancel() { |
| 284 | + try { |
| 285 | + mmSocket.close(); |
| 286 | + } catch (IOException e) { |
| 287 | + Log.e(TAG, "Could not close the connect socket", e); |
| 288 | + } |
| 289 | + } |
| 290 | + } |
| 291 | +} |
0 commit comments