1

My application needs to discover the nearby bluetooth devices. My working flow is like mentioned below:

Check Bluetooth state -> IF enabled -> disable it, then enable and search for nearby devices ELSE enable it and search for nearby devices.

I am using broadcast receiver to get nearby devices, but the problem is that the receiver is not being triggered.

Below is my code.

MyFragment.java:

public class MyFragment extends Fragment {

private BluetoothAdapter mBluetoothAdapter;
private ProgressDialog dialog;
private AlertDialog.Builder alertDialog;
boolean isBluetoothEnabledBySystem = false;
View view;

public MyFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view =  inflater.inflate(R.layout.fragment_my_fragment, container, false);     

    checkForBluetoothState();

    return view;
}

private void checkForBluetoothState()
{
    dialog = new ProgressDialog(getContext());
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(false);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter != null){

        if (mBluetoothAdapter.isEnabled())
        {
            if (isBluetoothEnabledBySystem == false)
            {
                askUserIfAnyDeviceConnected();
            }
        }
        else
        {
                new EnableBluetooth().execute();
        }

    }else
    {
        Toast.makeText(getActivity(), "Bluetooth not supported", Toast.LENGTH_SHORT).show();
    }
}

private void askUserIfAnyDeviceConnected() {

    alertDialog = new AlertDialog.Builder(getActivity());
    alertDialog.setCancelable(false);
    alertDialog.setTitle("Oops!");
    alertDialog.setMessage("It seems like your device is connected with another device via bluetooth.\nWould you like to disconnect it?");
    alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            new DisableBluetooth().execute();
        }
    });
    alertDialog.setNegativeButton("Later", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          Log.d("later","later");
        }
    }).create().show();
}

private class EnableBluetooth extends AsyncTask<Void,Void,Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setMessage("Enabling Bluetooth");
        dialog.show();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            Thread.sleep(2000);
            mBluetoothAdapter.enable();
            isBluetoothEnabledBySystem = true;

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        DiscoverBluetoothDevices();
    }
}

private class DisableBluetooth extends AsyncTask<Void,Void,Void>
{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setMessage("Disabling Bluetooth");
        dialog.show();

    }

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            Thread.sleep(2000);
            mBluetoothAdapter.disable();
            mBluetoothAdapter.enable();
            isBluetoothEnabledBySystem = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if (dialog != null && dialog.isShowing())
        {
            dialog.setMessage("Device enabled");
            dialog.show();
            DiscoverBluetoothDevices();
        }
    }
}

private void DiscoverBluetoothDevices()
{
    dialog.setMessage("Discovering Device");
    dialog.show();
    Log.d("adapter status","adapter status"+mBluetoothAdapter);
    mBluetoothAdapter.startDiscovery();

    IntentFilter bluetoothIntentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    getContext().registerReceiver(bluetoothBroadcast,bluetoothIntentFilter);
}

private final BroadcastReceiver bluetoothBroadcast = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("called receiver","called receiver");
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // A Bluetooth device was found
            // Getting device information from the intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.i("Device found", "Device found: " + device.getName() + "; MAC " + device.getAddress());
        }
    }
};


@Override
public void onPause() {
    super.onPause();
    getContext().unregisterReceiver(bluetoothBroadcast);
}

@Override
public void onDestroy() {
    super.onDestroy();
    getContext().unregisterReceiver(bluetoothBroadcast);
}
}

Let me know where is the error / mistake. Thanks in advance.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Eswar
  • 33
  • 2

1 Answers1

0

I think this is the one u looking :

Android Broadcast Receiver bluetooth events catching

Also check your manifest file or add which ever you need:

 <uses-feature android:name="android.hardware.bluetooth" />
 <uses-permission android:name="android.permission.BLUETOOTH" />
 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Also add broadcast receiver in the manifest, make sure u added the intent filter something similar to this

 <receiver android:name=".MyBroadcastReceiver"  android:exported="true">
<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED"/>
    <action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>

https://developer.android.com/guide/components/broadcasts

Jerry Abraham
  • 1,039
  • 18
  • 42