android蓝牙激活错误
我试图在android中通过编程激活蓝牙,应用程序安装良好,但当我点击按钮激活BT时,它给出了一个例外。我无法处理这个异常。非常感谢您的帮助。我是新来的。代码如下:android蓝牙激活错误,android,bluetooth,Android,Bluetooth,我试图在android中通过编程激活蓝牙,应用程序安装良好,但当我点击按钮激活BT时,它给出了一个例外。我无法处理这个异常。非常感谢您的帮助。我是新来的。代码如下: package com.example.helloandroid2; import java.io.IOException; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.content.Contex
package com.example.helloandroid2;
import java.io.IOException;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class HelloAndroid extends Activity {
// Declare our Views, so we can access them later
private Button activate_buletooth;
static final int REQUEST_ENABLE_BT = 0;
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set Activity Layout
setContentView(R.layout.main);
activate_buletooth = (Button)findViewById(R.id.activate_buletooth);
// Set Click Listener
activate_buletooth.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Context context = getApplicationContext();
CharSequence text = "BT not suported";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// startActivityForResult(discoverableIntent, REQUEST_ENABLE_BT);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == REQUEST_ENABLE_BT)
{
if(resultCode == RESULT_CANCELED)
{
Context context = getApplicationContext();
CharSequence text = "bt not available";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
}
}
}
}
这是由于默认情况下启用蓝牙适配器所需的时间。 我也有同样的问题,我找到了答案 此onclick事件之后预期执行的代码在适配器打开蓝牙之前执行。 有一种解决方案,比如有一个循环,在蓝牙完全打开之前不允许进一步的代码执行。或 有一种方法可以帮助你
欢迎任何进一步的帮助。从您的异常中可以追溯到什么?您是否已将BLUETOOTH和BLUETOOTH_ADMIN权限添加到应用程序的清单中?我已将BLUETOOTH_ADMIN添加到我的清单中,因为我正在手机上运行应用程序,所以无法获取异常。还是我错过了什么?