我无法通过蓝牙发送数据

时间:2016-09-25 19:05:04

标签: java android bluetooth

我在Android Studio中编写了应用程序,必须在Arduino Pro Mini上发送1。数据已发送但未到达Arduino。我通过蓝牙终端检查了Arduino,一切正常,所以问题在于代码。有什么问题?

package com.example.niko.motoco;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    BluetoothAdapter btAdapter = null ;
    BluetoothDevice btDevice = null;
    BluetoothSocket btSocket = null;

    final String LOG_TAG = "myLogs";
    Button btConnect, btSend;
    public TextView checkText;

    private static final int REQUEST_ENABLE_BT = 1;
    private static final int CONNECTEDdevice = 2;

    Boolean connection = false;
    private static String MAC = null;
    UUID my_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
    private ConnectedThread MyThread = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        checkText = (TextView) findViewById(R.id.checkText);
        btConnect = (Button)findViewById(R.id.btConnect);
        btSend = (Button)findViewById(R.id.btSend);

        btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter == null) {
            Toast.makeText(getApplicationContext(),"Device does not support Bluetooth",Toast.LENGTH_LONG).show();
        } else if (!btAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }


        btConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (connection) {
                    // disconnect
                    try {
                        btSocket.close();
                        connection = false;
                        btConnect.setText("Connect");
                        Toast.makeText(getApplicationContext(),"Bluetooht is disconnected:",Toast.LENGTH_LONG).show();
                    } catch (IOException error) {
                        Toast.makeText(getApplicationContext(),"Error;" + error,Toast.LENGTH_LONG).show();
                    }
                } else {
                    // connect
                    Intent ListDevices = new Intent(MainActivity.this, ListDevices.class);
                    startActivityForResult(ListDevices,CONNECTEDdevice);
                }

            }
        });

        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyThread.write((byte) 1);
                Toast.makeText(getApplicationContext(),"Sending 1",Toast.LENGTH_LONG).show();
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                if(resultCode == Activity.RESULT_OK) {
                    Toast.makeText(getApplicationContext(),"bluetooth is activated",Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),"bluetooth is not activated",Toast.LENGTH_LONG).show();
                    finish();
                }
                break;

            case CONNECTEDdevice :
                if (resultCode == Activity.RESULT_OK) {
                    MAC = data.getExtras().getString(ListDevices.MACaddress);

                    btDevice = btAdapter.getRemoteDevice(MAC);

                    try {
                        btSocket = btDevice.createRfcommSocketToServiceRecord(my_UUID);

                        btSocket.connect();

                        connection = true;

                        btConnect.setText("Disconnect");

                        Toast.makeText(getApplicationContext(),"MAC of connected device:" + MAC,Toast.LENGTH_LONG).show();

                        MyThread = new ConnectedThread(btSocket);
                        //MyThread.start();

                    } catch (IOException error) {
                        connection = false;
                        Toast.makeText(getApplicationContext(),"Error:" + error,Toast.LENGTH_LONG).show();
                    }

                }else {
                    Toast.makeText(getApplicationContext(),"didn't get MAC",Toast.LENGTH_LONG).show();

                }

        }
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket btSocket2;
        private final OutputStream OutStream;

        public ConnectedThread(BluetoothSocket socket) {
            btSocket2 = socket;
            OutputStream tmpOut = null;


            try {
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            OutStream = tmpOut;
        }


        public void write(byte bytes) {
            try {
                OutStream.write(bytes);
            } catch (IOException e) { }
        }


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



} 

1 个答案:

答案 0 :(得分:0)

出了什么问题?至少这2个代码是错误的:

try {
    tmpOut = socket.getOutputStream();
} catch (IOException e) { }

后来:

try {
    OutStream.write(bytes);
} catch (IOException e) { }

当出现问题时,你会发现默默地异常,并且没有机会找出根本原因。

将代码更改为:

try {
    tmpOut = socket.getOutputStream();
} catch (IOException e) {
     Log.(TAG, "Fail to get socket output stream" ,e);
}

后来:

try {
     OutStream.write(bytes);
} catch (IOException e) {
     Log.(TAG, "Fail to write on socket output stream" ,e);
}

然后重新运行代码并查看logcat。您可能会看到问题的原因。