有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过蓝牙向Android发送字节时发生java错误

我在安卓系统中通过蓝牙发送字节方面遇到了很大的困难,我想明确地说,我已经看过了一些教程和安卓开发者页面

我的应用程序的基本功能是打开/关闭蓝牙,搜索设备并连接到它们,列出配对设备并连接到它们,它有一个控件(它们只是发送数据的图像按钮),我必须记录用户何时搜索设备以及何时想要查看配对设备的活动,以便如果发送数据在其中一个设备上有效,则可以在另一个设备上有效

我的困难在于发送数据,显然我在代码中做了一些错误的事情。我已经用toast饱和了代码,以了解我何时执行应用程序的某些步骤(一旦我完成应用程序的最后一步,此toast将被删除)

在这些饱和状态下,我发现我的代码实际上发送了字节,但似乎没有发送它们,这是我不知道如何解决的问题(我的代码连接到另一个蓝牙设备-它甚至停止闪烁红色LED指示灯来告诉我,日志告诉我我已连接到它),我甚至复制了一些代码,将其更改为我的一部分,并执行我希望它执行的操作

我的XML具有所有必要的权限

代码:

public class SerachDevices extends ActionBarActivity {

private final BluetoothAdapter BT = BluetoothAdapter.getDefaultAdapter();
private BluetoothDevice bluetoothDevice;

ListView FoundD;
ImageButton btBUp;
ImageButton btBDown;
ImageButton btBLeft;
ImageButton btBRigth;
ImageButton btBStop;


String mensaje;    private ArrayAdapter<String> discoveredDevices;
int Gone = View.GONE;
int Visible = View.VISIBLE;
ConexionABluetooth conectar;


//Metod to find devices
public void Descubrir() {

    BT.startDiscovery();

    if (BT.startDiscovery()) {

        mensaje = "Buscando dispositivos";
        Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_SHORT).show();

    } else {

        mensaje = "Fallo la busqueda de dispositivos";
        Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_SHORT).show();
    }
}


//Reciever for found device
private final BroadcastReceiver FoundDReciever = new BroadcastReceiver() {


    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {

            bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            discoveredDevices.add(bluetoothDevice.getName() + "\n" + bluetoothDevice.getAddress());
        }
    }
};


//Brings up the imageviews, to control the robot
public void btControl(View view) {
    if (!BT.isEnabled()) {

        mensaje = "Activate bluetooth to use control";
        Toast.makeText(getBaseContext(), mensaje, Toast.LENGTH_SHORT).show();

    } else {

        FoundD.setVisibility(Gone);

        btBUp.setVisibility(Visible);
        btBDown.setVisibility(Visible);
        btBLeft.setVisibility(Visible);
        btBRigth.setVisibility(Visible);
        btBStop.setVisibility(Visible);

    }
}

public void btUp(View view) {
    if(BT.isEnabled()){
        String w = "w";

        conectar.write(w);
        Toast.makeText(getBaseContext(), w, Toast.LENGTH_SHORT).show();
    }else{

        mensaje = "make sure you have \nan active bluetooth connection";
    }

}

public void btDown(View view) {
    if(BT.isEnabled()){
        String s = "s";

        conectar.write(s);
        Toast.makeText(getBaseContext(), s, Toast.LENGTH_SHORT).show();
    }else{

        mensaje = "make sure you have \n" +
                "an active bluetooth connection";
    }
}

public void btLeft(View view) {
    if(BT.isEnabled()){
        String a = "a";

        conectar.write(a);
        Toast.makeText(getBaseContext(), a, Toast.LENGTH_SHORT).show();
    }else{

        mensaje = "make sure you have \n" +
                "an active bluetooth connection";
    }
}

public void btRigth(View view) {
    if(BT.isEnabled()){
        String d = "d";

        conectar.write(d);
        Toast.makeText(getBaseContext(), d, Toast.LENGTH_SHORT).show();
    }else{

        mensaje = "make sure you have \n" +
                "an active bluetooth connection";
    }
}

public void btStop(View view) {
    if(BT.isEnabled()){
        String q = "q";

        conectar.write(q);
        Toast.makeText(getBaseContext(), q, Toast.LENGTH_SHORT).show();
    }else{

        mensaje = "make sure you have \n" +
                "an active bluetooth connection";
    }
}


@Override
protected void onResume() {
    super.onResume();
    // Register the BroadcastReceiver for ACTION_FOUND
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(FoundDReciever, filter);
}

@Override
protected void onPause() {
    super.onPause();

    this.unregisterReceiver(FoundDReciever);
}

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

    btBUp = (ImageButton) findViewById(R.id.btUp);
    btBDown = (ImageButton) findViewById(R.id.btDown);
    btBRigth = (ImageButton) findViewById(R.id.btRight);
    btBLeft = (ImageButton) findViewById(R.id.btLeft);
    btBStop = (ImageButton) findViewById(R.id.btStop);


    FoundD = (ListView) findViewById(R.id.btFoundD);
    discoveredDevices = new ArrayAdapter(this, 安卓.R.layout.simple_list_item_1);

    Descubrir();

    FoundD.setAdapter(discoveredDevices);

    FoundD.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            String itemValue = (String) FoundD.getItemAtPosition(position);

            String MAC = itemValue.substring(itemValue.length() - 17);

            BluetoothDevice bluetoothDevice = BT.getRemoteDevice(MAC);

            if (BT.isEnabled()) {

                conectar = new ConexionABluetooth(bluetoothDevice);
                conectar.start();


            } else if (!BT.isEnabled()) {

                mensaje = "Bluetooth is not activated";
                Toast.makeText(getBaseContext(), mensaje, Toast.LENGTH_SHORT).show();

            }
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_serach_devices, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

////////////////////////////////////////////////////////////////////////////////
public class ConexionABluetooth extends Thread {


    public OutputStream btOutputStream = null;
    private BluetoothDevice btShield;
    public BluetoothSocket mySocket = null;
    private UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    public ConexionABluetooth(BluetoothDevice bluetoothShield) {

        btShield = bluetoothShield;
        try {
            mySocket = btShield.createRfcommSocketToServiceRecord(SPP_UUID);

            try {
                BT.cancelDiscovery();
                mySocket.connect();
                try {
                    btOutputStream = mySocket.getOutputStream();
                    mensaje = "Output catched";
                    Toast.makeText(getBaseContext(), mensaje, Toast.LENGTH_SHORT).show();

                } catch (IOException e) {
                    Log.e("ConnectToBluetooth", "Error when getting output Stream");
                }
            } catch (IOException e) {
                Log.e("ConnectToBluetooth", "Error with Socket Connection");

            }
        } catch (IOException e) {
            Log.e("ConnectToBluetooth", "Error with Socket Creation");

            try {
                mySocket.close();
            } catch (IOException closeException) {
                Log.e("ConnectToBluetooth", "Error Closing socket");
            }
            return;
        }
    }


    @Override
    public void run() {

        Log.d("fail to send", "...In onPause()...");

        if (btOutputStream != null) {
            try {
                btOutputStream.flush();
            } catch (IOException e) {
                Log.d("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
            }
        }


        try {
            mySocket.connect();
        } catch (IOException connectException) {
            try {
                mySocket.close(); //try to close the socket
            } catch (IOException closeException) {
            }
            return;
        }
    }


public void write(String str) {

    try {
        byte[] sd = str.getBytes();
        mensaje = "Message send";
        Toast.makeText(getBaseContext(), mensaje, Toast.LENGTH_SHORT).show();
        btOutputStream.write(sd);
    } catch (IOException e) {
        Log.e("Writing to Stream", "Error when writing to btOutputStream");
    }
}

    public void cancel() {
        try {
            mySocket.close();
        } catch (IOException e) {
        }
    }
}
}

共 (0) 个答案