如何在没有用户确认的情况下以编程方式设置可发现时间?

Tia*_*ago 7 java android bluetooth

我经常使用这个

private void ensureDiscoverable() {
    if(D) Log.d(TAG, "ensure discoverable");
    if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);
    }
}
Run Code Online (Sandbox Code Playgroud)

但这会提示用户确认.有没有办法以编程方式绕过这个?

另外,我认为"永远可发现的模式 " 上没有"新闻"?

Tia*_*ago 6

经过一些研究后,我得出结论,在没有用户交互的情况下设置可发现的超时,它只能通过root访问(如前面的答案中已经提到的那样).但是对于需要的人来说,这是必要的解决方案:

private void ensureBluetoothDiscoverability() {
    try {
        IBluetooth mBtService = getIBluetooth();
        Log.d("TESTE", "Ensuring bluetoot is discoverable");
        if(mBtService.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Log.e("TESTE", "Device was not in discoverable mode");
            try {
                mBtService.setDiscoverableTimeout(100);
                // mBtService.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 1000);
            } catch(Exception e) {
                Log.e("TESTE", "Error setting bt discoverable",e);
            }
            Log.i("TESTE", "Device must be discoverable");
        } else {
            Log.e("TESTE", "Device already discoverable");
        }
    } catch(Exception e) {
        Log.e("TESTE", "Error ensuring BT discoverability", e);
    }    
}
Run Code Online (Sandbox Code Playgroud)


<uses-permission android:name="android.permission.WRITE_SETTINGS" />  
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
Run Code Online (Sandbox Code Playgroud)

然后创建一个新的包android.bluetooth,里面放上IBluetooth.aidl和IBluetoothCallback.aidl两个文件,把里面的代码所示这里.

这将允许访问标准API上不可用的功能,但对于其中一些功能,您将需要"编写安全设置"的权限(上面的注释行是您将因缺少进程权限而获得该异常的位置/用户).