Android TV开发使用谷歌官方推荐方法开启蓝牙可被搜索:
Intent discoverableIntent =
new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
在移动端上该代码功能正常,但是在TV上会抛错:
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.bluetooth.adapter.action.REQUEST_DISCOVERABLE (has extras) }
经过各种检索发现很多人都反馈此问题,但是却没有给出具体解决方案,后面经过咨询公司内资深同事后发现通过反射即可解决此问题:
Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
setDiscoverableTimeout.setAccessible(true);
Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
setScanMode.setAccessible(true);
setDiscoverableTimeout.invoke(adapter, 0);
setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 0);