Bonus

Voici un code d'exemple pour utiliser le Bluetooth sur le legoNXT

Sur le lego :

BluetoothCommunicator.java
package fr.esiee.gyroway;


import lejos.nxt.Button;
import lejos.nxt.LCD;
import java.io.*;

import lejos.realtime.RealtimeThread;
import lejos.realtime.ReleaseParameters;
import lejos.realtime.SchedulingParameters;
import lejos.util.Datalogger;

/**
 * Class to handle Bluetooth communication with the legway. Includes a Thread to check incoming data.
 * Includes a method to use the NXTPilot program (not made by us).
 * 
 * @author Alexandre Barsacq
 *
 */
public class BluetoothCommunicator extends RealtimeThread{

    private DataInputStream inputStream;
    private DataOutputStream outputStream;

    //Constants for NXTPilot
    private final int NXTPilotFORWARD=1;
    private final int NXTPilotBACKWARD=2;
    private final int NXTPilotLEFT=3;
    private final int NXTPilotRIGHT=4;
    private final int NXTPilotSTOP=5;

    private int reception=NXTPilotSTOP;
    private int old=NXTPilotSTOP;
    private float turnCommand=0;
    private float forwardCommand=0;

    private boolean flag=false;
//  public static Datalogger dl=new Datalogger();

    /**
     * Creates a new instance of BluetoothCommunicator.
     * @param sched scheduling parameters for real-time thread
     * @param release release parameters for real-time thread
     * @param input input bluetooth stream (has to be opened before)
     * @param output output bluetooth stream (has to be opened before)
     */
    public BluetoothCommunicator(SchedulingParameters sched, ReleaseParameters release,DataInputStream input,DataOutputStream output)
    {   
        super(sched,release);
        inputStream=input;
        outputStream=output;
    }

    //Running : reads BT stream and updates the values to apply
    public void run(){

        while(!Button.ENTER.isPressed()){

            readCommandNXTPilot();
            waitForNextPeriod();

        }
    }



    /**
     * Reads commands sent by bluetooth and updates the values to apply.
     * method designed to use "NXT Pilot" program on Android. Retrieves data
     * over bluetooth and translates it into legway-usable data. 
     * 
     * @throws IOException 
     */
    private void readCommandNXTPilot()
    {

        try {
            //if nothing available, do nothing
            if(inputStream.available()>0)
            {   
                reception=inputStream.read();   
//              dl.writeLog(reception); 

                /*All this part is because of the weird protocol sent by
                 * the App. It translates it into usable data for our robot
                 * 
                 * The protocol sends :
                 * 0 before each command, so we ignore them
                 * 1,2,3,4,5 for : forward, backward,left,right,stop
                 * BUT ALSO, it sends a 2 (backward) each time a new command is
                 * pressed. 
                 * This part of the code makes sure that we don't go backward before
                 * each new command. Sadly, it creates a latency because we have
                 * to apply the old command waiting for the new one.  The latency equals 2 periods 
                 * of the thread (=20 ms as for the time this comment is written)
                 */
                if(reception==NXTPilotBACKWARD && flag!=true)
                {
                    reception=old;
                    flag=true;
                }
                else if(reception!=0 && flag==true) 
                {
                    flag=false;
                }
                old=reception;

                //The actual updating of the commands 
                switch(reception)
                {
                case NXTPilotFORWARD :
                    turnCommand=0;
                    forwardCommand=100;
                    break;
                case NXTPilotBACKWARD:
                    turnCommand=0;
                    forwardCommand=-100;
                    break;
                case NXTPilotLEFT:
                    turnCommand=100;
                    forwardCommand=0;
                    break;
                case NXTPilotRIGHT:
                    turnCommand=-100;
                    forwardCommand=0;
                    break;
                case NXTPilotSTOP:
                    turnCommand=0;
                    forwardCommand=0;
                    break;

                default :
                    break;

                }
            }
        } catch (IOException e) {
            LCD.drawString("FUCK", 0, 4);
        }


    }

    /**
     * Returns the last read turning command over bluetooth
     * @return turning command (between -100 and +100)
     */
    public float getTurnCommand(){
        return turnCommand;
    }

    /**
     * Returns the last read forward command over bluetooth
     * @return forward command (between -100 and +100)
     */
    public float getForwardCommand(){
        return forwardCommand;

    }


}

Sur le tel android :

BluetoothCommService.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package fr.umlv.nxtpilot.bluetooth;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import fr.umlv.nxtpilot.core.MenuActivity;

/**
 * The Service is used to connect to a NXT Robot. It handles a bluetooth connection to a NXT Bot. 
 * The Service can be bound from an Activity to be used.
 */
public class BluetoothCommService extends Service {

    private static final String TAG = "ConServ";
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    public static final int  IGNORE_MESSAGES=0;
    public static final int  NOTIFY_MESSAGES=1;
    public static final int STATE_CONNECTING = 1;
    public static final int STATE_NONE = 0;
    public static final int STATE_CONNECTED = 2;



    private   final LocalBinder b = new LocalBinder();
    private int mState;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private BluetoothAdapter mAdapter;
    private Handler mHandler;
    //private BluetoothSocket mSocket;
    //private BluetoothDevice mDevice;
    private boolean initialized;

    @Override
    public IBinder onBind(Intent arg0) {
          Log.d(TAG, "BIND");
        return b;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "UNBIND");
        return true;
    }



    /**
     * Initialize the Service with the given Handler
     * @param hand the handler given by an activity
     */
    public void initialize(Handler hand)
    {
        mHandler=hand;
        if(!initialized)
        {

         mAdapter = BluetoothAdapter.getDefaultAdapter();
            mState = STATE_NONE;
        }
    }

    /**
     * Create a bluetooth connection to a bluetooth device. 
     * It will start a thread which will start the connection to the device.
     * The return from this method doesn't mean that the connection is done or have failed.
     * @param device the device to be connected
     */
      public void connect(BluetoothDevice device) {

         Log.d(TAG, "connect to: " + device);



        // Cancel any thread attempting to make a connection
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Start the thread to connect with the given device
        mConnectThread = new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);

    }

      /**
       * This Method is called when the connection is done(ie the ConnectThread gone well) .
       * It will launch a new Thread which will handle the reading from the socket.
       * @param socket the socket to the bluetooth device.
       * @param device The bluetooth device which is connected
       */
        private synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
            Log.d(TAG, "connected");

            // Cancel the thread that completed the connection
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

            // Cancel any thread currently running a connection
            if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}



            // Start the thread to manage the connection and perform transmissions
            mConnectedThread = new ConnectedThread(socket);
            mConnectedThread.start();

            // Send the name of the connected device back to the UI Activity
            Message msg = mHandler.obtainMessage(MenuActivity.MESSAGE_DEVICE_NAME);
            Bundle bundle = new Bundle();
            bundle.putString(MenuActivity.DEVICE_NAME, device.getName());
            msg.setData(bundle);
            mHandler.sendMessage(msg);

            setState(STATE_CONNECTED);
        }

        /**
         * Stop all threads.
         */
        public synchronized void cancel() {
           Log.d(TAG, "stop");
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
            if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

            setState(STATE_NONE);

        }



        /**
         * Set's the state of the connection.
         * The handlers used to communicate with activities are informed that the state changed
         * @param state the new connection state
         */
        private synchronized void setState(int state) {
          Log.d(TAG, "setState() " + mState + " -> " + state);
            mState = state;

            // Give the new state to the Handler so the UI Activity can update
            mHandler.obtainMessage(MenuActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
        }

      /** 
       * This class is a thread wich will create the connection to the given device.
       */
      private class ConnectThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final BluetoothDevice mmDevice;

            /**
             * Constructor of the ConnectThread
             * @param device The device wich will be connected
             */
            public ConnectThread(BluetoothDevice device) {
                mmDevice = device;
                BluetoothSocket tmp = null;

                // Get a BluetoothSocket for a connection with the
                // given BluetoothDevice
                try {
                    tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e) {
                    Log.e(TAG, "create() failed", e);
                }
                mmSocket = tmp;
            }

            /**
             * The main content that will do the connection
             */
            @Override
            public void run() {
                Log.i(TAG, "BEGIN mConnectThread");
                setName("ConnectThread");

                // Always cancel discovery because it will slow down a connection
                mAdapter.cancelDiscovery();

                // Make a connection to the BluetoothSocket
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    mmSocket.connect();
                } catch (IOException e) {
                    connectionFailed();
                    // Close the socket
                    try {
                        mmSocket.close();
                    } catch (IOException e2) {
                        Log.e(TAG, "unable to close() socket during connection failure", e2);
                    }
                    // Start the service over to restart listening mode
                   // BluetoothCommService.this.start();
                    return;
                }

                // Reset the ConnectThread because we're done
                synchronized (BluetoothCommService.this) {
                    mConnectThread = null;
                }

                // Start the connected thread
                connected(mmSocket, mmDevice);
            }

            /**
             * Cancel the connection
             */
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) {
                    Log.e(TAG, "close() of connect socket failed", e);
                }
            }
        }

      /**
       * This thread is used when the connection is done. It will handle the read/write on the socket.
       * The connection is closed after 60 seconds of inactivity
       *
       */
      private class ConnectedThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final OutputStream mmOutStream;
            private BufferedReader mmBufReader;
            private long timeout=60000;
            private long lastDate;
            private Timer t = new Timer();
            private TimerTask tt = new TimerTask() {

                @Override
                public void run() {
                    Log.d(TAG, "Test date : last = "+(lastDate+timeout)+" current = "+System.currentTimeMillis());
                    if(lastDate+timeout<System.currentTimeMillis())
                    {
                        connectionLost();
                        ConnectedThread.this.cancel();

                    }

                }
            };

            public ConnectedThread(BluetoothSocket socket) {
                Log.d(TAG, "create ConnectedThread");
                mmSocket = socket;
                InputStream tmpIn = null;
                OutputStream tmpOut = null;
                lastDate=System.currentTimeMillis();


                // Get the BluetoothSocket input and output streams
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) {
                    Log.e(TAG, "temp sockets not created", e);
                }

                mmOutStream = tmpOut;
                mmBufReader=new BufferedReader(new InputStreamReader(tmpIn));

            }

            /**
             * Will initialize the Timer wich check the timeout of the connection.
             * After the initialization, an infinite loop of reading is launched.
             * If a message come from the NXT, the Activitie's handler is noticed, and the message is sent to it.
             */
            public void run() {
                Log.i(TAG, "BEGIN mConnectedThread");
                //start of timeout check
                t.schedule(tt, 0, 2000);

                // Keep listening to the InputStream while connected
                while (true) {
                    try {
                        // Read from the InputStream
                        //bytes = mmInStream.read(buffer);
                        String s=mmBufReader.readLine();

                            // Send the obtained bytes to the UI Activity
                            mHandler.obtainMessage(MenuActivity.MESSAGE_FROM_NXT, s.length(), -1, s).sendToTarget();


                        Log.i(TAG, "Something was read : "+s);
                    } catch (IOException e) {
                        Log.e(TAG, "disconnected", e);
                        connectionLost();
                        break;
                    }
                    //Whatever the exception happening, the loop should'nt be stopped, the show must go on :)
                    catch (Exception e) {
                        Log.e(TAG, "disconnected", e);
                        connectionLost();
                        cancel();
                        break;
                    }
                }
            }


            /**
             * Write to the connected OutStream (The NXT) and update the lastDate (for the connection timeout).
             * @param buffer  The bytes to write
             */
            public void write(byte[] buffer) {
                try {
                    lastDate=System.currentTimeMillis();

                    mmOutStream.write(buffer);

                    // Share the sent message back to the UI Activity
                    mHandler.obtainMessage(MenuActivity.MESSAGE_WRITE, -1, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "Exception during write", e);
                    connectionLost();
                   this.cancel();
                }
            }

            /**
             * 
             * Closes the connection
             */
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) {
                    Log.e(TAG, "close() of connect socket failed", e);
                }
                catch(Exception e)
                {
                    //Nothing to say, silent close
                }
            }
        }

    /**
     * Create a localbinder for the activities using the bluetooth service.
     *
     */
    public class LocalBinder extends Binder {
          public BluetoothCommService getService() {
                return BluetoothCommService.this;
            }
        }

    /**
     * Indicate that the connection failed and notify the UI Activity.
     */
    private void connectionFailed() {
        setState(STATE_NONE);

        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(MenuActivity.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(MenuActivity.TOAST, "Unable to connect device");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {


        setState(STATE_NONE);

        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(MenuActivity.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(MenuActivity.TOAST, "Device connection was lost");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }



    public void write(byte[] b)
    {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread

        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        r.write(b);
    }


    /**
     * The Service is started as STICKY
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_STICKY;
    }

    /**
     * This method is used to modify the new handler wich will be used to communicate with activities.
     * @param mHandler2 the new handler
     */
    public void setHandler(Handler mHandler2) {
        this.mHandler=mHandler2;

    }

    /**
     * On destroy, the connection is closed
     */
 @Override
public void onDestroy() {
    super.onDestroy();
    cancel();
}

}
Devices.java
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.umlv.nxtpilot.bluetooth;

import java.util.Set;

import fr.umlv.nxtpilot.R;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

/**
 * This Activity appears as a dialog. It lists any paired devices and
 * devices detected in the area after discovery. When a device is chosen
 * by the user, the MAC address of the device is sent back to the parent
 * Activity in the result Intent.
 */
public class Devices extends Activity {
    // Debugging
    private static final String TAG = "DeviceListActivity";
    // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    // Member fields
    private BluetoothAdapter mBtAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Setup the window
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.device_list);

        // Set result CANCELED incase the user backs out
        setResult(Activity.RESULT_CANCELED);

        // Initialize the button to perform device discovery
        Button scanButton = (Button) findViewById(R.id.button_scan);
        scanButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                doDiscovery();
                v.setVisibility(View.GONE);
            }
        });

        // Initialize array adapters. One for already paired devices and
        // one for newly discovered devices
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

        // Find and set up the ListView for paired devices
        ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(mDeviceClickListener);

        // Find and set up the ListView for newly discovered devices
        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
        newDevicesListView.setOnItemClickListener(mDeviceClickListener);

        // Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);

        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);

        // Get the local Bluetooth adapter
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();

        // Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        } else {
            String noDevices = getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(noDevices);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Make sure we're not doing discovery anymore
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }


        // Unregister broadcast listeners
        this.unregisterReceiver(mReceiver);
    }

    /**
     * Start device discover with the BluetoothAdapter
     */
    private void doDiscovery() {
        Log.d(TAG, "doDiscovery()");

        // Indicate scanning in the title
        setProgressBarIndeterminateVisibility(true);
        setTitle(R.string.scanning);

        // Turn on sub-title for new devices
        findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

        // If we're already discovering, stop it
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBtAdapter.startDiscovery();
    }

    // The on-click listener for all devices in the ListViews
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Cancel discovery because it's costly and we're about to connect
            mBtAdapter.cancelDiscovery();

            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            // Create the result Intent and include the MAC address
            Intent intent = new Intent();
            intent.putExtra(EXTRA_DEVICE_ADDRESS, address);


            // Set result and finish this Activity
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    };

    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };

}