importPackage(android.bluetooth);
importPackage(android.content);
importClass(java.util.concurrent.CountDownLatch);
importClass(java.util.concurrent.TimeUnit);
function enableBt() {
var a = BluetoothAdapter.getDefaultAdapter();
if (a == null) throw new Error("不支持蓝牙");
a.enable();
return a;
}
function withPan(adapter, fn) {
var latch = new CountDownLatch(1);
var out = { v: false };
adapter.getProfileProxy(context, new BluetoothProfile.ServiceListener({
onServiceConnected: function(p, proxy) {
if (p == BluetoothProfile.PAN) {
out.v = fn(proxy);
adapter.closeProfileProxy(BluetoothProfile.PAN, proxy);
}
latch.countDown();
},
onServiceDisconnected: function() {
latch.countDown();
}
}), BluetoothProfile.PAN);
latch.await(2, TimeUnit.SECONDS);
return out.v;
}
function toggleBluetoothTethering(context) {
var adapter = enableBt();
var state = withPan(adapter, function(p) { return p.isTetheringOn(); });
withPan(adapter, function(p) { p.setBluetoothTethering(!state); });
return state ? "蓝牙网络共享已关闭" : "蓝牙网络共享已开启";
}
toggleBluetoothTethering(context);
// 通过蓝牙共享手机的网络连接#Javascript