gpt4 book ai didi

android - 以编程方式在 Android 上启用蓝牙

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:00:02 24 4
gpt4 key购买 nike

我正在尝试确定以编程方式在 Android 上启用蓝牙的首选方式。我发现以下任一技术都有效(至少在 Android 4.0.4 上...):

public class MyActivity extends Activity {
public static final int MY_BLUETOOTH_ENABLE_REQUEST_ID = 6;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, MY_BLUETOOTH_ENABLE_REQUEST_ID);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == MY_BLUETOOTH_ENABLE_REQUEST_ID) {
if (resultCode == RESULT_OK) {
// Request granted - bluetooth is turning on...
}
if (resultCode == RESULT_CANCELED) {
// Request denied by user, or an error was encountered while
// attempting to enable bluetooth
}
}
}

或者...

BluetoothAdapter.getDefaultAdapter().enable();

前者在启用之前询问用户许可,而后者只是默默地启用蓝牙(但需要“android.permission.BLUETOOTH_ADMIN”许可)。一种或另一种是旧的/过时的和/或一种技术是否仅在某些设备上可用?还是只是个人喜好问题?

最佳答案

在AndroidDoc中明确提到

Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.

这两种技术都行得通。您必须根据您的目的和要求进行选择。希望它能回答您的问题。

关于android - 以编程方式在 Android 上启用蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22562606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com