2

我需要持续监控每 5 秒出现一次的蓝牙设备。我编写了以下不适合我的代码。

private static final int DISCOVERY_REQUEST = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth_connection);

    final TextView tv = (TextView) findViewById(R.id.textView1);
    tv.setText("");
    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
            .getDefaultAdapter();
    mBluetoothAdapter.startDiscovery();
    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);
                tv.append(device.getName() + "-"
                        + /* device.getAddress()+ */"\n");
                tv.append("here");
                /*
                 * if (device.getName().equals("ONCEWASCUT-L7")) {
                 * tv.append("this is in the vicinity");
                 * 
                 * }
                 */
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                tv.append("\nEntered the Finished\n ");
                mBluetoothAdapter.startDiscovery();
            }
        }

    };
    String aDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
    startActivityForResult(new Intent(aDiscoverable), DISCOVERY_REQUEST);
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);
    mBluetoothAdapter.startDiscovery();
}

需要添加什么代码才能使应用程序正常工作。请注意,我需要每 5 秒监控一次蓝牙设备。

4

2 回答 2

0

您可以使用 Timer 和 TimerTask 持续检查特定设备是否可用。

例如:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask {
    @Override
    public void run () {
        //Here you can use handler or whatever you want to use.
    }
},delay, period);

延迟 - 首次执行前的毫秒数。

period - 后续执行之间的时间量(以毫秒为单位)。

http://developer.android.com/reference/java/util/Timer.html#scheduleAtFixedRate

有关更多详细信息,请参阅此链接。

于 2013-04-29T12:11:35.243 回答
0

声明处理程序,根据您的要求更改时间

mhandler = new Handler();
            Runnable mrunnable = new Runnable() {
                @Override
                public void run() {
                    if (mBluetoothAdapter.isDiscovering()) {
                        mBluetoothAdapter.cancelDiscovery();
                    }
                    mBluetoothAdapter.startDiscovery();
                    mhandler.postDelayed(this, 1000);
                }
            };
            mhandler.post(mrunnable);
于 2020-04-07T10:33:27.773 回答