做自媒体查找素材的网站,网站开发的任务要求,自己建网站要学什么,推广网站利润最近工作中遇到一个特殊的需求#xff0c;要求代码能够从后台开机android手机蓝牙的可见性。而framework提供了一种打开可见性的操作#xff0c;就是通过向用户弹出一个提示框#xff0c;来询问是否允许开启可见性。而且限制了最长时间为300秒#xff0c;代码如下#xff…最近工作中遇到一个特殊的需求要求代码能够从后台开机android手机蓝牙的可见性。而framework提供了一种打开可见性的操作就是通过向用户弹出一个提示框来询问是否允许开启可见性。而且限制了最长时间为300秒代码如下//启动修改蓝牙可见性的IntentIntent intent new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//设置蓝牙可见性的时间方法本身规定最多可见300秒intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);startActivity(intent);但通过android的自带的settings程序我们可以直接开机蓝牙可见性。所以下载settings的源码进行分析。找到了开启蓝牙可见性的代码如下public void setDiscoverableTimeout(inttimeout) {BluetoothAdapter adapterBluetoothAdapter.getDefaultAdapter();try{Method setDiscoverableTimeout BluetoothAdapter.class.getMethod(setDiscoverableTimeout, int.class);setDiscoverableTimeout.setAccessible(true);Method setScanModeBluetoothAdapter.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();}}用这种方法开启的可见性还有个附件的属性timeout值并没有起到作用可见性是一直保持的。可以通行下面类似的代码进行关闭public voidcloseDiscoverableTimeout() {BluetoothAdapter adapterBluetoothAdapter.getDefaultAdapter();try{Method setDiscoverableTimeout BluetoothAdapter.class.getMethod(setDiscoverableTimeout, int.class);setDiscoverableTimeout.setAccessible(true);Method setScanModeBluetoothAdapter.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();}}改变BluetoothAdapter.SCAN_MODE_CONNECTABLE是关键。如果想实现超时后自动关闭可见性的效果使用HandlerpostDelayed(Runnable r, long delayMillis)就可以轻松实现这个功能。以上代码在android4.2以上可以允许4.2以下会因为缺少系统权限而运行失败。