最近工做中遇到一个特殊的需求,要求代码可以从后台开机android手机蓝牙的可见性。而framework提供了一种打开可见性的操做,就是经过向用户弹出一个提示框,来询问是否容许开启可见性。并且限制了最长时间为300秒,代码以下:java
//启动修改蓝牙可见性的Intent Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //设置蓝牙可见性的时间,方法自己规定最多可见300秒 intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(intent);
但经过android的自带的settings程序,咱们能够直接开机蓝牙可见性。因此下载settings的源码,进行分析。找到了开启蓝牙可见性的代码,以下:android
public void setDiscoverableTimeout(int timeout) { BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter(); 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(); } }
用这种方法开启的可见性,还有个附件的属性,timeout值并无起到做用,可见性是一直保持的。能够通行下面相似的代码进行关闭:post
public void closeDiscoverableTimeout() { BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter(); 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(); } }
改变BluetoothAdapter.SCAN_MODE_CONNECTABLE是关键。spa
若是想实现超时后自动关闭可见性的效果,使用Handlercode
就能够轻松实现这个功能。blog
以上代码在android4.2以上能够容许,4.2如下会由于缺乏系统权限而运行失败。get