来自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);
}
Run Code Online (Sandbox Code Playgroud)
但问题是如何在课堂上使用它?为什么我的代码会在点击此活动的按钮时崩溃:
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);
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
您是否在AndroidManifest.xml文件中设置了适当的权限?当然,您需要BLUETOOTH获得许可.
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
...
</manifest>
Run Code Online (Sandbox Code Playgroud)
此外,正如文件所述:
如果您希望应用启动设备发现或操作蓝牙设置,则还必须声明
BLUETOOTH_ADMIN权限.
如果要启用这些功能之一,则需要以下代码:
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
...
</manifest>
Run Code Online (Sandbox Code Playgroud)
在调用以下方法之前
!mBluetoothAdapter.isEnabled()
Run Code Online (Sandbox Code Playgroud)
在适配器上,您必须确保 mBluetoothAdapter 不为空。在您的情况下,它必须为空并崩溃。如果 mBluetoothAdapter 为空,则 android 文档说明该设备不支持蓝牙。
| 归档时间: |
|
| 查看次数: |
10616 次 |
| 最近记录: |