//会弹出一个确认框提醒用户
Intent discoverableIntent = newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);startActivity(discoverableIntent);
//没有界面的调用
public void setDiscoverableTimeout(){ ClsUtils.setDiscoverableTimeout(adapter,0);//这里设置时间无效,只能通过延迟close LogUtil.e("setDiscoverableTimeout"); new Handler().postDelayed(new Runnable() { @Override public void run() { closeDiscoverableTimeout(); LogUtil.e("closeDiscoverableTimeout"); } }, 10000);//毫秒单位 }
private void closeDiscoverableTimeout(){ closeDiscoverableTimeout(adapter); }public void setDiscoverableTimeout(BluetoothAdapter adapter,int timeout) { try { 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, timeout); setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE,timeout); } catch (Exception e) { e.printStackTrace(); } }public void closeDiscoverableTimeout(BluetoothAdapter adapter) { try { 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, 1); setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE,1); } catch (Exception e) { e.printStackTrace(); } }