Android 为什么socket.getOutputStream()返回null?

Android 为什么socket.getOutputStream()返回null?,android,sockets,bluetooth,arduino-uno,Android,Sockets,Bluetooth,Arduino Uno,我正在尝试创建一个android应用程序,使用HC-05蓝牙收发器与Arduino Uno R3通信。当我尝试在openBT中打开的套接字上使用getOutputStream时,它返回null 这是我的密码: import android.content.BroadcastReceiver; import android.content.Context; import android.content.IntentFilter; import android.os.Bundle; import a

我正在尝试创建一个android应用程序,使用HC-05蓝牙收发器与Arduino Uno R3通信。当我尝试在openBT中打开的套接字上使用getOutputStream时,它返回null

这是我的密码:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.bluetooth.*;
import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.io.IOException;
import java.io.DataOutputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

public static BluetoothAdapter mBluetoothAdapter =     BluetoothAdapter.getDefaultAdapter();
private static final int REQUEST_ENABLE_BT = 1;
private ArrayAdapter<String> mArrayAdapter;
BluetoothDevice mmDevice;
BluetoothSocket mmSocket;
OutputStream mmOutputStream;
InputStream mmInputStream;
DataOutputStream out;
String LEDOn = "zero";
String msg = "zero";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
    final TextView mTextView = (TextView) this.findViewById(R.id.myLabel);

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    // If there are paired devices
    if (pairedDevices.size() > 0) {
        // Loop through paired devices
        for (BluetoothDevice device : pairedDevices) {
            if (device.getName().equals("HC-05")) {
                mmDevice = device;
                mTextView.setText("Connected to " + mmDevice.toString());
            }
            // Add the name and address to an array adapter to show in a ListView
            // mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
        try {
            openBT();
        } catch (IOException e) {
        }

    } else {
        discover();
    }

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (LEDOn == "zero") {
                LEDOn = "one";
            } else {
                LEDOn = "zero";
            }
            try {
                sendData();
            } catch (IOException e) {
            }
        }
    });
}

public void discover() {
    final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                mBluetoothAdapter.cancelDiscovery();
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Add the name and address to an array adapter to show in a ListView
                mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        }
    };
    // Register the BroadcastReceiver
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);
}

void openBT() throws IOException {
    final UUID MY_UUID = UUID.fromString("4eb3ab89-05e4-4180-b530-964c7ed2d83e");
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
    mmSocket.connect();
    try {
        if (mmSocket.isConnected()) {
            mmOutputStream = mmSocket.getOutputStream();
        } else {
            System.out.println("mmOutputStream = " + mmOutputStream.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    mmInputStream = mmSocket.getInputStream();
}

void sendData() throws IOException {
    try {
        msg = LEDOn;
        mmOutputStream.write(msg.getBytes());
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

@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_main, 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);
}
}
在我的Arduino方面,代码如下所示:

#include <SoftwareSerial.h>// import the serial library

SoftwareSerial bluetooth(2, 3); // RX, TX
int ledpin = 13; // led on D13 will show blink on / off
char BluetoothData; // the data given from Computer

void setup() {
  // put your setup code here, to run once:
  bluetooth.begin(9600);
  bluetooth.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (bluetooth.available()) {
    BluetoothData = bluetooth.read();
    if (BluetoothData == 'one') { // if number 1 pressed ....
      digitalWrite(ledpin, 1);
      bluetooth.println("LED  On D13 ON ! ");
    }
    if (BluetoothData == 'zero') { // if number 0 pressed ....
      digitalWrite(ledpin, 0);
      bluetooth.println("LED  On D13 Off ! ");
    }
  }
  delay(100);// prepare for next data ...
}

任何帮助都将不胜感激。我已经搜索了这个网站和谷歌几个小时,试图找到答案

你在盲目地呼唤openBT;即使找不到您的设备。您正在调用openBT;从而打开主线程上的蓝牙插座。你确定这是允许的吗?”普通的“套接字”只能在一个线程中打开。我使用了全新的android开发和蓝牙编程,所以我不知道我还能把openBT放在哪里;这与android或蓝牙无关。你没看到代码总是调用openBT吗?只有在找到您的设备时,您才应该这样做。您正在检查您的设备是否已经存在。因此,承担后果。这里有一些混乱。将调用放入线程或异步任务中。