以编程方式重启蓝牙

时间:2018-10-16 09:48:58

标签: android android-asynctask bluetooth

在执行另一种方法之前,我将如何以编程方式重启android蓝牙并等待蓝牙打开。

我想执行以下操作,但是要等到蓝牙适配器完全重新启动后,再停止执行其他代码:How to enable/disable bluetooth programmatically in android

1 个答案:

答案 0 :(得分:1)

您需要收听蓝牙状态并进行相应的操作

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();
    }
}

现在,您只需要使用上下文创建此类的实例,并使用RestartListener调用重新启动方法。您将获得回调。