gpt4 book ai didi

android - 如何通过点击请求Android用户启用蓝牙?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:59:44 26 4
gpt4 key购买 nike

来自 http://developer.android.com/guide/topics/connectivity/bluetooth.html我知道我需要执行以下操作来请求用户启用他的 BT:

if (!mBluetoothAdapter.isEnabled()) 
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

但问题是如何在类里面使用它?为什么每次单击此 Activity 的按钮时我的代码都会崩溃:

public class Opponents extends Activity 
{
private final static int REQUEST_ENABLE_BT=1;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

@Override
protected void onCreate(Bundle savedInstancesState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.opponents);

final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
}

最佳答案

您是否在 AndroidManifest.xml 文件中设置了适当的权限?当然,您需要 BLUETOOTH 权限。

<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
...
</manifest>

此外,如文档所述:

If you want your app to initiate device discovery or manipulate Bluetooth settings, you must also declare the BLUETOOTH_ADMIN permission.

如果您想要启用这些功能之一,您将需要以下代码:

<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
...
</manifest>

关于android - 如何通过点击请求Android用户启用蓝牙?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28411991/

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