蓝牙发现一个AsyncTask的内 [英] Bluetooth discovery inside a AsyncTask

查看:137
本文介绍了蓝牙发现一个AsyncTask的内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图搜索附近的蓝牙设备,来完成这项任务正在使用的AsyncTask 的code为我的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);
     }
}

正如你所看到的 doInBackground 函数返回的所有设备的ArrayList。我的问题是,这份名单中不包含任何对象都没有。我'肯定我启用了设备这是可发现任何提示将AP preciated

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

在此先感谢!

修改

再下边是我的清单文件:

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>

编辑#2

我尝试添加一个虚拟对象进入榜单,而不是跟随code的行

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());

我试过

devices.add("Test");

但是,当我调试,该ArrayList仍然是空的?

But when I debug, the arraylist is still empty?

推荐答案

首先,Java没有的功能。它的方法

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

所有的二,你不应该使用的AsyncTask 在这里。 的AsyncTask s的用于执行潜在的昂贵的操作关闭UI线程。蓝牙发现是异步的,所以你不要需要引入多线程来发现其他设备。此外,它看起来像所有你在你的的AsyncTask 是定义和注册一个新的广播接收器操作。这将在数​​毫秒执行(创建/执行实际的AsyncTask 甚至可能需要更长的时间)。这样一来,你的 onPostExecute 方法将被调用的立即的您注册接收器之后。这可能是什么困惑你。

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.

请通过Android的蓝牙此​​文档读...它会逐步引导您完成设置您的蓝牙发现应用程序的过程。

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

这篇关于蓝牙发现一个AsyncTask的内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆