2017-07-19 83 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 
    // ...   
}