2017-07-19 56 views
0

正如您所看到的,我制作了一个应用程序,可将数据从Android设备发送到蓝牙模块。除了一件小事:除了一件小事外,一切都可以完美运行:每当我打开应用程序时,我都应该已经通过手机设置打开蓝牙,否则应用程序会崩溃,打开蓝牙后必须重新打开它,以便它能够正常运行。通过在Android和Arduino之间传输数据实现蓝牙问题

我设计了一个蓝牙点击监听器按钮,但它仍然崩溃,而我通过按钮启用它。

你能帮我找到我的代码中的错误吗?

public class MainActivity extends AppCompatActivity { 
    private static final String TAG = "bluetooth1"; 
    Button btnsend ; 
    EditText edttext ; 
    Button btnOnOff; 
    private BluetoothAdapter btAdapter = null; 
    private BluetoothSocket btSocket = null; 
    private OutputStream outStream = null; 
    // 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 String address = "20:16:06:28:17:83"; 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    btnsend = (Button) findViewById(R.id.btnsend); 
    edttext = (EditText) findViewById(R.id.edttxt); 
    btnOnOff = (Button) findViewById(R.id.btnOnOff); 
    btAdapter = BluetoothAdapter.getDefaultAdapter(); 
    btnOnOff.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View view) { 
     if (btAdapter.isEnabled()) { 
      btAdapter.disable(); 
      Toast.makeText(getApplicationContext(), " Disabling Bluetooth", Toast.LENGTH_SHORT).show(); 
     } else { 
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableBtIntent,1); 
      Toast.makeText(getApplicationContext(), " Enabling Bluetooth", Toast.LENGTH_SHORT).show(); 
     } 
     } 
    }); 
    edttext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD); 
    edttext.setTransformationMethod(new NumericKeyBoardTransformationMethod()); 
    btnsend.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View view) { 
     String dataTransmit = edttext.getText().toString(); 
     if (dataTransmit != null) { 
      sendData(dataTransmit); 
     } else { 
      Toast.makeText(getApplicationContext(), "Please type something first", Toast.LENGTH_SHORT).show(); 
     } 
     } 
    }); 
    } 

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { 
    if(Build.VERSION.SDK_INT >= 10) { 
     try { 
     final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class }); 
     return (BluetoothSocket) m.invoke(device, MY_UUID); 
     } catch (Exception e) { 
     Toast.makeText(getBaseContext(), "Could not Insecure", Toast.LENGTH_SHORT).show(); 
     } 
    } 
    return device.createRfcommSocketToServiceRecord(MY_UUID); 
    } 
    @Override 
    public void onResume() { 
    super.onResume(); 
    // Set up a pointer to the remote node using it's 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 e1) { 
     errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + "."); 
    } 
    btAdapter.cancelDiscovery(); 
    // Establish the connection. This will block until it connects. 
    Toast.makeText(getBaseContext(), "Connecting", Toast.LENGTH_SHORT).show(); 
    try { 
     btSocket.connect(); 
     Toast.makeText(getBaseContext(), "Connecting Ok", Toast.LENGTH_SHORT).show(); 
    } 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 server. 
    try { 
     outStream = btSocket.getOutputStream(); 
    } catch (IOException e) { 
     errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + "."); 
    } 
    } 
    @Override 
    public void onPause() { 
    super.onPause(); 
    if (outStream != null) { 
     try { 
     outStream.flush(); 
     } catch (IOException e) { 
     errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + "."); 
     } 
    } 
    try { 
     btSocket.close(); 
    } catch (IOException e2) { 
     errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + "."); 
    } 
    } 
    private void errorExit(String title, String message) { 
    Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show(); 
    finish(); 
    } 

    private void sendData(String message) { 
    byte[] msgBuffer = message.getBytes(); 
    try { 
     outStream.write(msgBuffer); 
    } catch (IOException e) { 
     String msg = "In onResume() and an exception occurred during write: " + e.getMessage(); 
     if (address.equals("20:16:06:28:17:83")) 
     msg = msg + ".\n\nUpdate your server address from 20:16:06:28:17:83 to the correct address on line 35 in the java code"; 
     msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n"; 
     errorExit("Fatal Error", msg); 
    } 
    } 
} 

回答

0

您必须检查BT是否启用。试试这个:

protected void checkBTState() { 
    mBtAdapter = BluetoothAdapter.getDefaultAdapter(); 
    if(mBtAdapter == null) { 
     String message = getResources().getText(R.string.bluetooth_not_supported).toString(); 
     Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show(); 
    } else { 
     if (mBtAdapter.isEnabled()) { 
      Log.d(TAG, "...Bluetooth ON..."); 
     } else { 
      // Prompt user to turn on Bluetooth // 
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableBtIntent, 1); 
     } 
    } 
} 

放入的onResume

@Override 
public void onResume() { 
    super.onResume(); 
    checkBTState(); 
    // ... 
    // some code 
    // ...   
}