来自 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/