简体   繁体   中英

Android: Error in discovering bluetooth devices

I need some help in my Android application. I am trying to create an app that discovers bluetooth devices then compare the name to a string. but I encountered 2 problems.

1: when I exit the app (back button) it exits then show me a crash message (after few seconds) .. I think the problem is with "mReceiver" (check "2nd problem).

2:(main problem) In the code bellow, the $"mReceiver = new BroadcastReceiver()" part has a problem. I have thrown multiple toasts every where just to check which part doesn't work, everything before this line works fine.

I'm not sure but I think the problem with not having "final" in declaring "mReciver" in the beginning --> "private BroadcastReceiver mReceiver;". However adding final causes problems.

The Code:

public class MainActivity extends Activity {

private final static int REQUEST_ENABLE_BT = 1; //It's really just a number that you provide for onActivityResult (>0)

//Temp objects for testing
private String StringMeeting = "meeting";
ProgressBar bar;

//Member fields
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;

// Create a BroadcastReceiver for ACTION_FOUND
private BroadcastReceiver mReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //declare & start progress bar
    bar = (ProgressBar) findViewById(R.id.progressBar1);
    bar.setVisibility(View.VISIBLE);

    //------------Setup a Bluetooth (Get Adapter) ------------------
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        // Device does not support Bluetooth
        Toast.makeText(getApplicationContext(), "This Device does not support Bluetooth", Toast.LENGTH_LONG).show();
    }else{Toast.makeText(getApplicationContext(), "Getting the Adabter is done", Toast.LENGTH_SHORT).show();}


    //------------Setup a Bluetooth (Enable Bluetooth) ------------------
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }else{Toast.makeText(getApplicationContext(), "Enable Bluetooth is done", Toast.LENGTH_SHORT).show();}

    //------------Finding Devices (Discovering Devices)----------------------
    // Create a BroadcastReceiver for ACTION_FOUND
    Toast.makeText(getApplicationContext(), "creating the mReceiver", Toast.LENGTH_SHORT).show(); //last thing works
    mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "accessed onReceive + will create action", Toast.LENGTH_SHORT).show();
            String action = intent.getAction();

            Toast.makeText(getApplicationContext(), "Waiting to discover a device", Toast.LENGTH_SHORT).show();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                Toast.makeText(getApplicationContext(), "enterd the if", Toast.LENGTH_SHORT).show();
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Toast.makeText(getApplicationContext(), "Getting device names", Toast.LENGTH_SHORT).show();
                Toast.makeText(getApplicationContext(), device.getName(), Toast.LENGTH_LONG).show();
                Toast.makeText(getApplicationContext(), "displaying the name should be done", Toast.LENGTH_SHORT).show();

                // Add the name and address to an array adapter to show in a ListView
                mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());

            }else{Toast.makeText(getApplicationContext(), "Error: BluetoothDevice.ACTION_FOUND.equals(action) = False", Toast.LENGTH_SHORT).show();}
        }
    };
    // Register the BroadcastReceiver
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy


} //onCreate end

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

    // Make sure we're not doing discovery anymore
    if (mBluetoothAdapter != null) {
        mBluetoothAdapter.cancelDiscovery();
    }

    // Unregister broadcast listeners
    this.unregisterReceiver(mReceiver);
}
}

Thank You For Your Time.

You start an activity for result in order for the user to be prompted whether the user allows Bluetooth to be enabled or not, but you don't wait for the result and try to find devices right away.

You should implement onActivityResult call back. If the result is RESULT_OK, then you start discovering devices. Enabling bluetooth takes some time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM