基于OmarAflak蓝牙库的Android蓝牙APP崩溃问题求助
Hey there! Let's work through those two NullPointerExceptions you're hitting with your Android Bluetooth app—since you're new to Bluetooth development, I'll break this down clearly with actionable fixes tailored to the OmarAflak library you're using.
Issue 1: NullPointerException when calling bluetooth.send("test") in MainActivity
Root Cause
The stack trace points to an empty OutputStream, which means you're trying to send data before the Bluetooth connection is fully established. The library's connection process is asynchronous—clicking a device and immediately calling send() doesn't wait for the connection to complete.
Fix Steps
Wait for the connection success callback before sending data
The library triggers anonConnected()callback once the connection is ready. Move yoursend()call to this method instead of calling it directly in the device click handler.Modify your MainActivity code like this:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize Bluetooth with callback bluetooth = new Bluetooth(this); bluetooth.setCallback(this); // ... rest of your initialization code } // Device click handler private void onDeviceClicked(BluetoothDevice device) { // Only initiate connection here—don't send data yet bluetooth.connect(device); } // Override the library's connection success callback @Override public void onConnected(BluetoothDevice device) { Toast.makeText(this, "Connected to " + device.getName(), Toast.LENGTH_SHORT).show(); // Now it's safe to send data bluetooth.send("test"); } // Don't forget to override other required callbacks @Override public void onConnectionFailed(BluetoothDevice device) { Toast.makeText(this, "Connection failed", Toast.LENGTH_SHORT).show(); } @Override public void onDisconnected(BluetoothDevice device) { Toast.makeText(this, "Disconnected", Toast.LENGTH_SHORT).show(); }Verify Bluetooth permissions are set up correctly
Ensure yourAndroidManifest.xmlhas all necessary permissions (adjust for your target SDK):<!-- For Android 11 and below --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- For Android 12+ --> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />Also, request runtime permissions for
ACCESS_FINE_LOCATION(Android 6+) andBLUETOOTH_CONNECT(Android 12+) before attempting connections.
Issue 2: NullPointerException when calling connectToAddress(address) in SecondActivity
Root Cause
Even if your bluetoothObject and address are non-null, the library requires proper initialization (including binding to its internal service) before calling connectToAddress(). Missing lifecycle hooks or callback setup can lead to hidden null references inside the library.
Fix Steps
Properly initialize the Bluetooth object in SecondActivity
You need to set the callback, and tie the library's lifecycle to your Activity's lifecycle:public class SecondActivity extends AppCompatActivity implements BluetoothCallback { private Bluetooth bluetooth; private String deviceAddress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // Get the address from Intent deviceAddress = getIntent().getStringExtra("DEVICE_ADDRESS"); // Initialize Bluetooth with callback bluetooth = new Bluetooth(this); bluetooth.setCallback(this); } @Override protected void onStart() { super.onStart(); // Bind to the library's service (critical for connection functionality) bluetooth.onStart(); } @Override protected void onStop() { super.onStop(); // Unbind the service to prevent leaks bluetooth.onStop(); } // Call connectToAddress after the Activity is started (e.g., in onResume) @Override protected void onResume() { super.onResume(); if (deviceAddress != null && bluetooth != null) { // Check if Bluetooth is enabled first if (bluetooth.isEnabled()) { bluetooth.connectToAddress(deviceAddress); } else { // Request user to enable Bluetooth bluetooth.enable(); } } } // Override required callbacks to handle connection status @Override public void onConnected(BluetoothDevice device) { Toast.makeText(this, "Connected to " + device.getName(), Toast.LENGTH_SHORT).show(); // You can send data here too } @Override public void onConnectionFailed(BluetoothDevice device) { Toast.makeText(this, "Connection failed to " + device.getAddress(), Toast.LENGTH_SHORT).show(); } // ... implement other BluetoothCallback methods }Validate the MAC address format
Ensure thedeviceAddressyou're passing is a valid Bluetooth MAC address (format:XX:XX:XX:XX:XX:XX). Even a small typo here can cause internal errors in the library.
Additional Troubleshooting Tips
- Check Bluetooth state: Always verify Bluetooth is enabled before attempting connections using
bluetooth.isEnabled(). If not, callbluetooth.enable()to prompt the user. - Update the library: Make sure you're using the latest version of OmarAflak's Bluetooth Library—older versions may have bugs that cause unexpected NPEs.
- Log detailed info: Add logs to track when
bluetoothis initialized, whenconnectToAddressis called, and what thedeviceAddressvalue is. This helps pinpoint where the null reference is coming from.
内容的提问来源于stack exchange,提问作者Nunna Yobusiness

