Android蓝牙通信呼叫写入方法

时间:2018-03-09 17:19:32

标签: java android bluetooth communication

我试图直接从Android教程中使用MyBluetoothService类,并按照文本的建议从主活动中调用write方法。我想了解一些关于如何将字符串从主活动传递到write方法并将其发送到连接的蓝牙设备的指导。

      $file_db = new PDO('sqlite:myfile.sqlite');
      $file_db->setAttribute(PDO::ATTR_ERRMODE,
   PDO::ERRMODE_EXCEPTION);

1 个答案:

答案 0 :(得分:0)

此代码将帮助您查找周围的所有设备

    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle; 
    import android.view.View; 
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;
    import java.util.ArrayList;
     import java.util.List;
     import java.util.Set;

    public class DeviceList extends AppCompatActivity {
    ListView blist;
    Button b;
    private BluetoothAdapter myBluetooth = null;
    private Set<BluetoothDevice> pairedDevices;
    public static String EXTRA_ADDRESS = "device_address";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_device_list);



    b=(Button)findViewById(R.id.button);
    blist=(ListView)findViewById(R.id.listView);



    myBluetooth = BluetoothAdapter.getDefaultAdapter();

    if(myBluetooth == null)
    {
        //Show a mensag. that the device has no bluetooth adapter
        Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();

        //finish apk
        finish();
    }
    else if(!myBluetooth.isEnabled())
    {
        //Ask to the user turn the bluetooth on
        Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(turnBTon,1);
    }

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pairedDevices();
        }
    });

}
private void pairedDevices()
{
    pairedDevices=myBluetooth.getBondedDevices();
    ArrayList list=new ArrayList();
    if(pairedDevices.size() > 0)
    {

        for(BluetoothDevice bt : pairedDevices)
        {
            list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
        }
    }
    else
    {
        Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
    }

    final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
    blist.setAdapter(adapter);
    blist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked

}


private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
    public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
    {
        // Get the device MAC address, the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);

        // Make an intent to start next activity.
        Intent i = new Intent(DeviceList.this, ledControl.class);

        //Change the activity.
        i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
        startActivity(i);
    }
};
}

此代码有助于将消息发送到已连接的设备

  public class ledControl extends AppCompatActivity {


Button btnOn, btnOff, btnDis;
TextView lumn;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
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); //receive the address of the bluetooth device

    //view of the ledControl
    setContentView(R.layout.activity_led_control);

    //call the widgtes
    btnOn = (Button) findViewById(R.id.button2);
    btnOff = (Button) findViewById(R.id.button3);
    btnDis = (Button) findViewById(R.id.button4);
    lumn = (TextView) findViewById(R.id.lumn);

    new ConnectBT().execute(); //Call the class to connect

    //commands to be sent to bluetooth
    btnOn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            turnOnLed();
            //method to turn on

        }
    });

    btnOff.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            turnOffLed();   //method to turn off

        }
    });

    btnDis.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Disconnect(); //close connection
        }
    });
}

private void Disconnect()
{
    if (btSocket!=null) //If the btSocket is busy
    {
        try
        {
            btSocket.close(); //close connection
        }
        catch (IOException e)
        { msg("Error");}
    }
    finish(); //return to the first layout

}

private void turnOffLed()
{
    if (btSocket!=null)
    {
        try
        {


            btSocket.getOutputStream().write("F".toString().getBytes());
            //Log.e("message",)
        }
        catch (IOException e)
        {
            msg("Error");
        }
    }
}

private void turnOnLed()
{
    if (btSocket!=null)
    {
        try
        {
            //Toast.makeText(ledControl.this,"oning",Toast.LENGTH_SHORT).show();
            btSocket.getOutputStream().write("O".toString().getBytes());
            Log.e("message",btSocket.toString());
        }
        catch (IOException e)
        {
            msg("Error");
        }
    }
}

// fast way to call Toast
private void msg(String s)
{
    Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}


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(ledControl.this, "Connecting...", "Please wait!!!");  //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;
    }
    @Override
    protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
    {
        super.onPostExecute(result);

        if (!ConnectSuccess)
        {
            msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
            finish();
        }
        else
        {
            msg("Connected.");
            isBtConnected = true;
        }
        progress.dismiss();
    }
}
}