简体   繁体   English

我无法通过蓝牙发送数据

[英]I can't send the data through Bluetooth

I wrote the application in Android Studio which has to send 1 on Arduino Pro Mini. 我在Android Studio中编写了该应用程序,该应用程序必须在Arduino Pro Mini上发送1。 Data is sent but doesn't reach Arduino. 数据已发送但未到达Arduino。 I checked Arduino through Bluetooth Terminal and everything was OK so the problem is in code. 我通过蓝牙终端检查了Arduino,一切都很好,所以问题出在代码上。 What is wrong? 怎么了?

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) { }
        }
    }



} 

What's wrong ? 怎么了 ? At least those 2 pieces of code are wrong : 至少这两段代码是错误的:

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

And later: 然后:

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

When something goes wrong you catch the exception silently and loose all chances to identify the root cause. 当出现问题时,您会默默地捕获异常,并失去所有找出根本原因的机会。

Change the code to something like this : 将代码更改为如下所示:

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

And later : 然后 :

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

Then re-run your code and look at the logcat. 然后重新运行您的代码,并查看logcat。 You will probably see the cause of your problems. 您可能会看到问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM