安卓蓝牙激活错误
问题描述:
我想在android中以编程方式激活蓝牙,并且应用程序安装正常,但是当我点击按钮激活BT时,它会发出异常。我无法处理这个例外。任何帮助是极大的赞赏。我是新来的。这里是代码:安卓蓝牙激活错误
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()
事件在适配器切换蓝牙之前被执行后,预计将被“执行”的代码。 可以有一个解决方案,像有一个循环,它不会允许进一步的代码执行,直到蓝牙完全打开。或者 可以有一个setDelay()
类型的方法可以帮助。
欢迎任何进一步的帮助。
你的例外有什么追溯?你是否已将BLUETOOTH和BLUETOOTH_ADMIN权限添加到应用的清单中? – 2010-09-20 15:35:53
我在清单中添加了BLUETOOTH_ADMIN由于我在手机上运行应用程序,因此无法获得例外。或者我错过了什么? – JPro 2010-09-20 15:37:06