Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

Bluetooth discovery inside a AsyncTask

I am trying to search for nearby bluetooth devices, to accomplish this task am using an AsyncTask The code for my AsyncTask is underneath

public class DeviceScan extends AsyncTask<String, Void, ArrayList<String>> {


    ProgressDialog dialog;
    Context _context; 
    BluetoothAdapter adapter; 
    final BroadcastReceiver blueToothReceiver;


    /**
     * The constructor of this class
     * @param context The context of whatever activity that calls this AsyncTask. For instance MyClass.this or getApplicationContext()
     */

    public DeviceScan(Context context) {

        _context = context; 
        dialog = new ProgressDialog(_context); 
        adapter = BluetoothAdapter.getDefaultAdapter();
        blueToothReceiver = null; 

    }


    protected void onPreExecute() {

          dialog.setTitle("Please Wait");
          dialog.setMessage("Searching for devices..");
          dialog.setIndeterminate(true);
          dialog.setCancelable(false);
          dialog.show();

    }

    /*
     * Operations "behind the scene", do not interfere with the UI here!
     * (non-Javadoc)
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected ArrayList<String> doInBackground(String... params) {

        //This arraylist should contain all the discovered devices. 
        final ArrayList<String> devices = new ArrayList<String>();

        // Create a BroadcastReceiver for ACTION_FOUND
        final BroadcastReceiver blueToothReceiver = new BroadcastReceiver() {
            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);
                    // Add the name and address to an array adapter to show in a ListView
                    devices.add(device.getName() + "\n" + device.getAddress());
                }
            }
        };
        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        _context.registerReceiver(blueToothReceiver, filter);

        return devices;

    }


    /*
     * After the background thread has finished, this class will be called automatically 
     * (non-Javadoc)
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
     protected void onPostExecute(ArrayList<String> result) {
         dialog.dismiss(); 
         Toast.makeText(_context, "Finished with the discovery!", Toast.LENGTH_LONG).show(); 


     }

     protected void onDestory() {
          _context.unregisterReceiver(blueToothReceiver);
     }
}

As you can see the doInBackground function returns an Arraylist of all the devices. My problem is that this list doesn't contain any objects at all. I'am sure that I have enabled devices which are Discoverable Any tips will be appreciated

Thanks in advance!

EDIT

Underneath is my Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.com.com"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="11" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

EDIT #2

I tried to add a dummy object into the list, instead of following line of code

devices.add(device.getName().toString() + "\n" + device.getAddress().toString());

I tried

devices.add("Test");

But when I debug, the arraylist is still empty?

Upvotes: 1

Views: 4652

Answers (1)

Alex Lockwood
Alex Lockwood

Reputation: 83311

First of all, java doesn't have functions. It has methods.

Second of all, you shouldn't be using an AsyncTask here. AsyncTasks are used to perform potentially expensive operations off the UI thread. Bluetooth discovery is asynchronous, so you don't need to introduce multiple threads to discover other devices. Further, it looks like all that you are doing in your AsyncTask is defining and registering a new BroadCastReceiver. This will be executed in several milliseconds (creating/executing the actual AsyncTask might even take longer). As a result, your onPostExecute method will be invoked immediately after you register the receiver. This is probably what is confusing you.

Please read through this documentation on Bluetooth in Android... it will step you through the process of setting up your application for Bluetooth discovery.

Upvotes: 4

Related Questions