我创建了一个项目,将字符串从蓝牙发送到其他蓝牙设备。我的问题是,如果我在第一次活动中与蓝牙设备建立连接,我是否需要再次进行第二次活动?
private ProgressDialog progress;
public BluetoothAdapter myBluetooth = null;
public static BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS);
setContentView(R.layout.activity_led_vent_control);
init();
leds1 = (Switch) findViewById(R.id.switch1);
leds2 = (Switch) findViewById(R.id.switch2);
leds3 = (Switch) findViewById(R.id.switch3);
leds4 = (Switch) findViewById(R.id.switch4);
leds5 = (Switch) findViewById(R.id.switch5);
brightness = (SeekBar)findViewById(R.id.seekBar);
lumn=(TextView)findViewById(R.id.lumn);
btnDis=(Button)findViewById(R.id.btnDis);
new ConnectBT().execute(); //Call the class to connect
//commands to be sent to bluetooth
leds1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if(leds1.isChecked())
turnOnLed1(); //method to turn on
else turnOffLed1();
}
});
}
private void turnOnLed1()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("A".toString().getBytes());
l1=true;
}
catch (IOException e)
{
msg("Error");
}
}
}
答案 0 :(得分:0)
这是我的ConnectBT课程
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledVentControl.this, "Свързва се...", "Моля изчакайте!!!"); //show a progress dialog
}
@Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}