我试图在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
{
}
}
}
}
答案 0 :(得分:0)
这是由于默认适配器启用蓝牙所需的时间。 我遇到了同样的问题,我追查了它。
在适配器切换蓝牙之前执行此onClick()
事件后,预计将“执行”的代码。
可能有一个解决方案,比如有一个循环,在蓝牙完全打开之前不允许进一步的代码执行。要么
可以有setDelay()
种方法可以提供帮助。
欢迎任何进一步的帮助。