android studio java使用蓝牙错误从arduino接收数据

zujrkrfu  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(1009)

当我运行andriod应用程序时,通过bc417蓝牙与arduino连接后出现了以下问题:

I/GPUD: @gpudInitialize: successfully initialized with GL, dbg=0 mmdump_dbg=0 mmpath_dbg=0
E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@5e29f04
E/GED: Failed to get GED Log Buf, err(0)
V/ActivityThread: callActivityOnCreate
V/HwWidgetFactory:: successes to get AllImpl object and return...
I/DecorView[]:  old windowMode:0 new windoMode:1
D/receivedata: ...Bluetooth ON...
D/ActivityThread: add activity client record, r= ActivityRecord{5a9f488 token=android.os.BinderProxy@fefc6b1 {com.example.receivedata/com.example.receivedata.MainActivity}} token= android.os.BinderProxy@fefc6b1
D/receivedata: ...onResume - try connect...
D/receivedata: ...Connecting...
D/BluetoothSocket: BT connect calling pid/uid = 31322/10165
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
D/receivedata: ....Connection ok...
    ...Create Socket...
D/HiTouch_PressGestureDetector: onAttached, package=com.example.receivedata, windowType=1, mHiTouchRestricted=false
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface**, EGLBoolean) returns 0x3000
W/Gralloc3: mapper 3.x is not supported
E/gralloc: Arm Module v1.0
E/ion: ioctl c0044901 failed with code -1: Invalid argument
I/HwViewRootImpl: removeInvalidNode jank list is null
D/DecorView: showOrHideHighlightView: hasFocus=true; winMode=1; isMrgNull=true
W/InputMethodManager: startInputReason = 1
W/InputMethodManager: startInputReason = 5
I/QarthLog: [PatchStore] createDisableExceptionQarthFile
    [PatchStore] create disable file for com.example.receivedata uid is 10165
E/AndroidRuntime: FATAL EXCEPTION: Thread-2
    Process: com.example.receivedata, PID: 31322
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Message android.os.Handler.obtainMessage(int, int, int,java.lang.Object)' on a null object reference
        at com.example.receivedata.MainActivity$ConnectedThread.run(MainActivity.java:192)
D/receivedata: ...In onPause()...
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@f9b95cd, channel: 1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@6716e82, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@883d993mSocket: android.net.LocalSocket@7209dd0 impl:android.net.LocalSocketImpl@7d8c1c9 fd:java.io.FileDescriptor@ccbf0ce, mSocketState: CONNECTED
I/Process: Sending signal. PID: 31322 SIG: 9

该错误是连接后的运行时错误,当我的应用程序尝试从arduino接收数据时,出现以下问题:
e/androidruntime:致命异常:thread-2进程:com.example.receivedata,pid:31322 java.lang.nullpointerexception:尝试在com.example.receivedata.mainactivity$connectedthread.run(mainactivity)的空对象引用上调用虚拟方法“android.os.message android.os.handler.obtainmessage(int,int,int,java.lang.object)”。java:192)
arduino(java)代码:

package com.example.receivedata;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String TAG = "receivedata";
    TextView txtArduino;
    Handler h;

    final int RECIEVE_MESSAGE = 1;        // Status  for Handler
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private final StringBuilder sb = new StringBuilder();

    private ConnectedThread mConnectedThread;

    // SPP UUID service
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // MAC-address of Bluetooth module (you must edit this line)
    private static final String address = "98:D3:32:30:82:85";

    /**Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtArduino = findViewById(R.id.txtArduino);      // for display the received data from the Arduino

       @SuppressLint("HandlerLeak") Handler h = new Handler() {
            @SuppressLint({"HandlerLeak", "SetTextI18n"})
            public void handleMessage(android.os.Message msg) {
                if (msg.what == RECIEVE_MESSAGE) {                                                   // if receive massage
                    String readBuf = (String) msg.obj;
                    sb.append(readBuf);                                                // append string
                    int endOfLineIndex = sb.indexOf("\n");                            // determine the end-of-line
                    if (endOfLineIndex > 0) {                                            // if end-of-line,
                        String sbprint = sb.substring(0, endOfLineIndex);               // extract string
                        sb.delete(0, sb.length());                                      // and clear
                        txtArduino.append(String.format("BPM: %s", sbprint));
                        mConnectedThread.write("x");
                    }
                    //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                }
            };
        };

        btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
        checkBTState();
    }

    @SuppressLint("ObsoleteSdkInt")
    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        if(Build.VERSION.SDK_INT >= 10){
            try {
                final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
                return (BluetoothSocket) m.invoke(device, MY_UUID);
            } catch (Exception e) {
                Log.e(TAG, "Could not create Insecure RFComm Connection",e);
            }
        }
        return  device.createRfcommSocketToServiceRecord(MY_UUID);
    }

    @Override
    public void onResume() {
        super.onResume();

        Log.d(TAG, "...onResume - try connect...");

        // Set up a pointer to the remote node using its address.
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case, we are using the
        //     UUID for SPP.

        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

        // Discovery is resource-intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        Log.d(TAG, "...Connecting...");
        try {
            btSocket.connect();
            Log.d(TAG, "....Connection ok...");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
            }
        }

        // Create a data stream so we can talk to the server.
        Log.d(TAG, "...Create Socket...");

        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();
        //I send a character when resuming.beginning transmission to check device is connected
        //If it is not an exception will be thrown in the write method and finish() will be called
        mConnectedThread.write("x");

    }

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

        Log.d(TAG, "...In onPause()...");

        try     {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
        }
    }

    private void checkBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on
        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) {
            errorExit("Fatal Error", "Bluetooth not support");
        } else {
            if (btAdapter.isEnabled()) {
                Log.d(TAG, "...Bluetooth ON...");
            } else {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);

            }
        }
    }

    private void error exit(String title, String message){
        Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
    }

    //create new class for connect thread
    private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        //creation of the connect thread
        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try {
                //Create I/O streams for connection
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[256];
            int bytes=0;

            // Keep looping to listen for received messages
            while (true) {
                try {
                    buffer[bytes] = (byte) mmInStream.read();            //read bytes from input buffer
                    if((buffer[bytes] == '\n'))
                     // Send the obtained bytes to the UI Activity via handler
                    {
                        h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
                        bytes=0;
                    }
                    else
                        bytes++;
                } catch (IOException e) {
                    break;
                }
            }
        }
        //write method
        public void write(String input) {
            byte[] msgBuffer = input.getBytes();           //converts entered String into bytes
            try {
                mmOutStream.write(msgBuffer);                //write bytes over BT connection via outstream
            } catch (IOException e) {
                //if you cannot write, close the application
                Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();

            }
        }
    }

}

arduino代码:

char incomingByte;  // incoming data
int  LED = 13;      // LED pin
int BPM_Last=0;
void setup() {
  Serial.begin(9600); // initialization
  pinMode(LED, OUTPUT);
  Serial.println("Press 1 to LED ON or 0 to LED OFF...");
}

void loop() {
  int BPM=random(80, 100);
  //byte out[4];
  if (Serial.available() > 0) {  // if the data came
    if(incomingByte==' ')
      incomingByte = Serial.read(); // read byte
    if(incomingByte == 'x'&&BPM!=BPM_Last) {
       digitalWrite(LED, HIGH); // if 0, switch LED on
       Serial.println("LED ON. Press 0 to LED OFF!");
       /*for(int i=0;i<3;i++){
        out[i]=BPM%10;
        BPM/=10;
        }
        out[3]='\n';*/
       Serial.write(BPM);
       Serial.write('\n');
       incomingByte = ' ';       
       BPM_Last=BPM;
    }
    else
    {
       digitalWrite(LED, LOW);  // if 1, switch LED Off
       Serial.println("LED OFF. Press 1 to LED ON!");  // print message

    }
  }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题