我将如何以编程方式重新启动 android 蓝牙并等到蓝牙打开后再执行其他方法。
我想执行以下操作,但停止执行其他代码,直到蓝牙适配器完全重新启动: 如何在安卓中以编程方式启用/禁用蓝牙
您需要侦听蓝牙状态并相应地工作
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 调用重新启动方法。您将收到回调。
使用处理程序,您可以轻松重新启动蓝牙。
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialogConConnect.dismiss();
}
});
tvOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String sec = edtConC.getText().toString();
int second = Integer.parseInt(sec);
int minus = second - 1;
int mSecond = minus*1000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(bluetoothAdapter.isEnabled()){
bluetoothAdapter.disable();
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(!bluetoothAdapter.isEnabled()){
bluetoothAdapter.enable();
}
}
},1000);
}
},mSecond);
dialogConConnect.dismiss();
}
});
dialogConConnect.show();
}
});