1

我制作了一个使用蓝牙的应用程序

在该oncreate()方法中,它启用蓝牙并将设备设置为无限期可见

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    if(!adapter.isEnabled()) {

        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, REQUEST_ENABLE_BT);
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
        startActivity(discoverableIntent);
    }
}

onDestroy()它禁用蓝牙

protected void onDestroy() {
    // TODO Auto-generated method stub
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if(adapter.isEnabled()) {
        adapter.disable();
    }
    super.onDestroy();
}

但是当我退出应用程序后再次手动启用蓝牙时,它会自动设置为无限期可发现。

如何在功能Undiscoverable中禁用蓝牙之前将其设置为onDestroy()

仅在 Nexus 5 上测试

4

2 回答 2

0
  • 您似乎无法生成使设备不可发现的意图。
  • 所以,你需要解决这个问题。开始一个新的可发现意图一秒钟就可以了。
  • 它将可发现时间从无穷大缩短到一秒,这是我们可以让它变得不可发现的最接近的时间。
  • 我知道这是一种 hack,但 Android 文档中没有提供其他方法。

    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,1);
    startActivity(discoverableIntent);
    

蓝牙设备中可发现性的 Android 文档链接:http: //developer.android.com/guide/topics/connectivity/bluetooth.html#EnablingDiscoverability

这可能是问题的重复:在 Android 上禁用蓝牙可发现模式

于 2014-06-10T04:55:21.847 回答
0

这将启用 1 秒的可发现性,并使您免于被无限期发现

Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,1);
startActivity(discoverableIntent);
于 2014-06-10T03:41:02.490 回答