androidandroid-asynctaskbluetooth

Programmatically restarting Bluetooth


How would i restart android Bluetooth programmatically and wait till the Bluetooth is on before executing another method.

I would like to do the following but stop the execution of other code til the bluetooth adaptar has fully restarted: How to enable/disable bluetooth programmatically in android


Solution

  • You need to listen to Bluetooth states and work accordingly

    public class BluetoothRestarter {
    
    private Context mContext;
    private RestartListener mListener;
    private BroadcastReceiver mReceiver;
    
    public BluetoothRestarter(Context context) {
        mContext = context;
    }
    
    public void restart(RestartListener listener) {
        mListener = listener;
        if (mReceiver == null) {
            mReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                        final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                BluetoothAdapter.ERROR);
                        switch (state) {
                            case BluetoothAdapter.STATE_OFF:
                                BluetoothAdapter.getDefaultAdapter().enable();
                                break;
                            case BluetoothAdapter.STATE_ON:
                                mListener.onRestartComplete();
                                break;
                        }
                    }
                    context.unregisterReceiver(this);
                }
            };
            mContext.registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
        }
    }
    
    public interface RestartListener {
        void onRestartComplete();
        }
    }
    

    Now you just have to create instance of this class with a context and call restart method with a RestartListener. You will get the callback.