代码。
BluetoothAdapter ba;
ba=BluetoothAdapter.getDefaultAdapter();
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(ba==null)
{
}
else if(ba.isEnabled()==false)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(false);
builder.setTitle("Settings");
builder.setMessage("Do you Want to Turn on Bluetooth ?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
Intent m=new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{ public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
}
});
这是我的代码,我试图在点击按钮时检查蓝牙是否启用。但当我点击按钮时,应用程序崩溃了..
如何解决这个问题?我认为错误是,isEnabled()方法返回NULL值..我不确定这个错误。
答案 0 :(得分:0)
您是否启用了访问蓝牙的权限?
答案 1 :(得分:-1)
如果您这样做,首先您的代码会更容易:
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(ba != null || !ba.isEnabled())
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(false);
builder.setTitle("Settings");
builder.setMessage("Do you Want to Turn on Bluetooth ?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
Intent m=new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{ public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
}
});
所以你的问题是,如果你检查null并且它是null然后检查它是否已启用,但是ba对象是null,其下面的代码必须工作